[英]Is it possible to implement a BroadcastReceiver as a singleton if it's to be registered in the manifest?
[英]Android: Stop locationManager from updating within broadcastreceiver registered in manifest
我在清单文件中注册了BroadcastReceiver
,因此即使在应用程序被清除后,它也会收到位置更新。
<receiver android:name="com.tenforwardconsulting.cordova.bgloc.LocationReceiver">
<intent-filter>
<action android:name="myBroadcast" />
<action android:name="stopUpdating" />
</intent-filter>
</receiver>
打开应用程序时,它会使用pendingIntents
启动locationManager
。
Intent intent = new Intent(context, LocationReceiver.class);
intent.setAction("myBroadcast");
intent.putExtra("session_id", session_id);
//intent.addFlags(Intent.FLAG_FROM_BACKGROUND);
lpendingIntent = PendingIntent.getBroadcast(activity.getApplicationContext(), 58534, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//Register for broadcast intents
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 0, lpendingIntent);
这很好用,甚至在应用程序关闭后我会不断获得更新。 现在当我想停止获取更新时,我可以使用getComponentEnabledSetting()
设置我的BroadcastReceiver
并将其状态设置为禁用就好了。 但我很确定我的pendingIntent
将会持续每一分钟。 我似乎无法弄清楚如何阻止它。 我已经尝试在broadcastReceiver中重新创建它,就像这里的许多答案一样......
Intent intent1 = new Intent(context, LocationReceiver.class);
PendingIntent.getBroadcast(context, 58534, intent1, PendingIntent.FLAG_UPDATE_CURRENT).cancel();
但它每分钟都这样做后继续进入BroadcastReceiver
。 我在这里做错了吗?
您需要完全按照初始设置时重新创建PendingIntent,并调用removeUpdates()
以停止位置更新回调。
请注意,无需在PendingIntent上调用cancel()
。
另请注意,您需要以某种方式使用Application子类中的字段或使用SharedPreferences持久保存session_id
。 这是为了正确地重新创建PendingIntent所必需的。
因此,停止位置更新的代码将是这样的:
Intent intent = new Intent(context, LocationReceiver.class);
intent.setAction("myBroadcast");
intent.putExtra("session_id", session_id);
PendingIntent lpendingIntent = PendingIntent.getBroadcast(activity.getApplicationContext(), 58534, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//Unregister for broadcast intents
LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(lpendingIntent);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.