簡體   English   中英

Android:停止locationManager在manifest中注冊的broadcastreceiver中更新

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM