我在 list 文件中注册了一个 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
会持续每一分钟。我似乎不知道如何阻止它。我尝试在广播接收器内重新创建它,就像这里的许多答案一样......
Intent intent1 = new Intent(context, LocationReceiver.class);
PendingIntent.getBroadcast(context, 58534, intent1, PendingIntent.FLAG_UPDATE_CURRENT).cancel();
但每分钟执行此操作后,它都会继续访问 BroadcastReceiver
。我在这里做错了什么吗?
最佳答案
您需要按照最初设置时的样子重新创建 PendingIntent,并调用 removeUpdates()
以停止位置更新回调。
请注意,无需对 PendingIntent 调用 cancel()
。
另请注意,您需要以某种方式保留 session_id
,使用 Application 子类中的字段或使用 SharedPreferences。为了正确地重新创建 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);
关于java - Android:阻止 locationManager 在 list 中注册的广播接收器内更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36436619/