I'm on Android 2.3.7 and I'm trying to write a BroadcastReceiver that will get called when the user turns GPS on/off (ie: by tapping on the "use GPS satellites" in the options.
What I've done so far is this:
1) Created the following broadcastReceiver:
public class GPSStatusBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
Toast.makeText(arg0, "Broadcast received!", Toast.LENGTH_SHORT).show();
}
}
2)Added this to the android manifest, inside the tags:
<receiver android:name=".GPSStatusBroadcastReceiver">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
</intent-filter>
</receiver>
Now the problem with this is that it appears not to be reliable. When I turn GPS on/ff the onReceive() method only runs sometimes (I'd say 1 time out 3) the other times it doesn't get called.
I want to know if there is a reliable way to detect when the GPS is turned off/on.
If there isn't it would be nice to be notified at least when no app is using the GPS anymoer (ie: when the gps icon disappears from statusbar, indicating no one is actively locating).
EDIT: Clarification: I don't want to do this while my app is running. I just whatn my app to be started when gps is turned on/off, do its thing and then terminate, I don't want to subscribe to LocationsUpdates...
Under "Personal," tap Location access. At the top of the screen, turn Access to my location on or off. When location access is on, pick either or both of: GPS satellites: Lets your phone estimate its location from satellite signals, like a GPS device in a car.
If in your app, you want to listen to the GPS state change (I mean On/Off by user). Using a Broadcast surely is the best approach. Implementation: /** * Following broadcast receiver is to listen the Location button toggle state in Android.
On API level 9 and higher you can use LocationManager.PROVIDERS_CHANGED_ACTION
:
Broadcast intent action when the configured location providers change. For use with
isProviderEnabled(String)
. If you're interacting with theLOCATION_MODE API
, useMODE_CHANGED_ACTION
instead.Constant Value: "android.location.PROVIDERS_CHANGED"
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With