【问题标题】:Notice fragment or activity from broadcast receiver通知来自广播接收器的片段或活动
【发布时间】:2015-01-08 17:35:24
【问题描述】:

我需要来自广播接收器的通知片段/活动,但我找不到解决方案。

描述:当片段启动我的方法时,如果没有要求用户打开它,则检查 GPS 模块是否打开。现在我有 gps 的广播接收器,gps 何时打开或关闭我收到消息,这有效。但是现在我需要做一些类似界面的事情,当我收到 GPS 开/关时,我想在片段中调用我的方法。我不确定是否清楚我需要什么。在这里,我尝试使用接口,但后来我发现我无法将接口对象传递给广播接收器构造函数。

我的解决方案有界面但不工作:

    public class GpsLocationReceiver extends BroadcastReceiver {

    private INotifyGpsTurnedOn iNotifyGpsTurnedOn = null;

    public GpsLocationReceiver(INotifyGpsTurnedOn iNotifyGpsTurnedOn) {
        this.iNotifyGpsTurnedOn = iNotifyGpsTurnedOn;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        LocationManager lm = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);
        boolean isEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        Toast.makeText(context, isEnabled+"",
                Toast.LENGTH_SHORT).show();

        if(isEnabled){
            iNotifyGpsTurnedOn.iniGps();
        }
        else{
            iNotifyGpsTurnedOn.askTurnOnGps();
        }
    }

    public interface INotifyGpsTurnedOn {
        public void iniGps();
        public void askTurnOnGps();
    }
}

在片段类中,我实现了方法接口、注册接收器等...

 GpsLocationReceiver m_gpsChangeReceiver = new GpsLocationReceiver(this);
    getActivity().registerReceiver(m_gpsChangeReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));

    @Override
public void iniGps() {
    mGps.startGps(false);
}

@Override
public void askTurnOnGps() {
    mGps.askUserToTurnOnGPS(getActivity());
}

【问题讨论】:

  • 如果你的 Fragment 实现了接口 INotifyGpsTurnedOn 我不明白为什么这不起作用。你遇到了什么错误?
  • 我无法使用接口,因为我无法在 GpsLocationReceiver 的构造函数中传递 iNotifyGpsTurnedOn,在分机中是不允许的。广播接收器。
  • 当然可以。你遇到了什么错误?
  • 异常:无法实例化接收器没有空的构造函数...我也尝试添加空构造函数或调用 super 但结果仍然相同,然后我发现:BroadcastReceiver 除了默认值之外不能有其他构造函数。删除您创建的构造函数。链接:stackoverflow.com/questions/23269192/…
  • 什么时候出现这个错误?

标签: java android android-fragments gps broadcastreceiver


【解决方案1】:

这很好用。您可以声明 Interface 并在构造函数中提供它。只要您自己实例化 BroadcastReceiver 并且不要让 Android 这样做,它就可以工作。您无需在清单中声明此BroadcastReceiver

您得到Exception: Unable to instantiate receiver no empty constructor. 的原因是Android 正在尝试实例化BroadcastReceiver。 (无论出于何种原因)。

【讨论】:

  • 感谢大卫的帮助。我无法确认您的解决方案是否对我有用,因为我已经以不同的方式解决了它,但我认为您的解决方案会起作用并且我接受您的回答。谢谢你的时间。未来我会记住你的忠告。
猜你喜欢
  • 1970-01-01
  • 2011-10-09
  • 2020-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多