【发布时间】: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