I have a BroadcastReceiver
registered in the manifest file so that even after the app is wiped closed, it receives location updates.
<receiver android:name="com.tenforwardconsulting.cordova.bgloc.LocationReceiver">
<intent-filter>
<action android:name="myBroadcast" />
<action android:name="stopUpdating" />
</intent-filter>
</receiver>
When the app is opened, it starts a locationManager
using pendingIntents
.
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);
This works great and even after app is closed i keep getting updates. Now when I want to stop getting updates, I can set my BroadcastReceiver
using getComponentEnabledSetting()
and set it's state to disabled just fine. But I'm pretty sure my pendingIntent
would keep going through every minute. I can't seem to figure out how to stop it. I've tried recreating it inside the broadcastReceiver like many answers on here like so...
Intent intent1 = new Intent(context, LocationReceiver.class);
PendingIntent.getBroadcast(context, 58534, intent1, PendingIntent.FLAG_UPDATE_CURRENT).cancel();
But it just keeps on going through to the BroadcastReceiver
after doing this every minute. Am I doing something wrong here?
You need to re-create the PendingIntent exactly as it was when it was initially set up, and call removeUpdates()
in order to stop the location update callbacks.
Note that there is no need to call cancel()
on the PendingIntent.
Also note that you would need to persist the session_id
somehow, using a field in an Application subclass, or using SharedPreferences. This is needed in order to re-create the PendingIntent correctly.
So, your code to stop location updates would be something like this:
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);