Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: detect when GPS is turned on/off (or when no app is using it anymore)

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...

like image 490
Master_T Avatar asked Mar 16 '13 17:03

Master_T


People also ask

How do you check if GPS is on or off in Android?

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.

How can you tell if someone turned off their GPS state?

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.


1 Answers

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 the LOCATION_MODE API, use MODE_CHANGED_ACTION instead.

Constant Value: "android.location.PROVIDERS_CHANGED"

Source

like image 58
theWook Avatar answered Oct 02 '22 15:10

theWook