android – How to detect when user turn on/off gps state?-ThrowExceptions

Exception or error:

I want to block the user from changing WiFi, GPS and loading settings from my application. The user need not on/off WiFi and GPS while running my application.(From notification bar). Is there any BroadcastReceiver exist for listening GPS on/off?

How to solve:

Well I did a lot of digging and found that addGpsStatusListener(gpsStatusListener) was deprecated in API 24. And for me, this didn’t even work! So, here is another alternative solution to this.

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.
 */
private BroadcastReceiver mGpsSwitchStateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
            // Make an action or refresh an already managed state.
        }
    }
};

Don’t forget to register and unregister this efficiently in Fragment/Activity Lifecycle as well.

registerReceiver(mGpsSwitchStateReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));

For example, if you are using this a Fragment, register it in the onResume and unregister in the onDestroy. Also, if you are directing user to the settings to enable the Location Switch, unregistering in the onStop will not function since, your activity goes to onPause and Fragment is stopped.

Well there may be many answers for this solution but this one is easy to manage and use. Propose your solutions if any.

###

You can listen the GPS status with a GpsStatus.Listener
and register it with the LocationManager.

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.addGpsStatusListener(new android.location.GpsStatus.Listener()
{
    public void onGpsStatusChanged(int event)
    {
        switch(event)
        {
        case GPS_EVENT_STARTED:
            // do your tasks
            break;
        case GPS_EVENT_STOPPED:
            // do your tasks
            break;
        }
    }
});

You need to have access to the context (for example in an “Activity” or “Application” class).

###

This is not possible. You can’t control/restrict the state of the hardware on your whim. This would be dangerous to have in the APIs and rightfully so no such API exists.

###

You can register a BroadcastReceiver for listening to Intent Action PROVIDERS_CHANGED_ACTION. This will broadcast when the configured location provider changes. You can refer this link.

###

Listen LocationManager.PROVIDERS_CHANGED_ACTION events in your activity’s onResume() method:

IntentFilter filter = new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION);
filter.addAction(Intent.ACTION_PROVIDER_CHANGED);
mActivity.registerReceiver(gpsSwitchStateReceiver, filter);

Add this instance of BroadcastReceiver to your Activity:

private BroadcastReceiver gpsSwitchStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(intent.getAction())) {

                LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                if (isGpsEnabled || isNetworkEnabled) {
                    // Handle Location turned ON
                } else {
                    // Handle Location turned OFF
                }
            }
        }
    };

Unregister the receiver in your onPause() method:

mActivity.unregisterReceiver(gpsSwitchStateReceiver);

###

You can detect status of GPS by following way.

Look at GpsStatus.Listener. Register it with locationManager.addGpsStatusListener(gpsStatusListener).

Also check this SO link for better understanding.

###

Starting from API 19 you can register a BroadcastReceiver for listening to intent action LocationManager.MODE_CHANGED_ACTION

Reference: https://developer.android.com/reference/android/location/LocationManager.html#MODE_CHANGED_ACTION

You can get location mode with

try
{
    int locationMode = android.provider.Settings.Secure.getInt(context.getContentResolver(), android.provider.Settings.Secure.LOCATION_MODE);
} catch (android.provider.Settings.SettingNotFoundException e)
{
    e.printStackTrace();
}

Value returned should be one of the following:

android.provider.Settings.Secure.LOCATION_MODE_BATTERY_SAVING
android.provider.Settings.Secure.LOCATION_MODE_HIGH_ACCURACY
android.provider.Settings.Secure.LOCATION_MODE_OFF
android.provider.Settings.Secure.LOCATION_MODE_SENSORS_ONLY

###

You cannot use GpsStatus.Listener to do this. You must use broadcast receiver. Use LocationManager.PROVIDERS_CHANGE_ACTION. Not use Intent.ACTION_PROVIDER_CHANE.
Good luck !

###

I’m using android.location.LocationListener for this purpose:

`class MyOldAndroidLocationListener implements android.location.LocationListener {
    @Override public void onLocationChanged(Location location) { }

    //here are the methods you need
    @Override public void onStatusChanged(String provider, int status, Bundle extras) {}
    @Override public void onProviderEnabled(String provider) { }
    @Override public void onProviderDisabled(String provider) { }
}`

NOTE (from the docs): These methods are called if the LocationListener has been registered with the location manager service using the LocationManager.requestLocationUpdates(String, long, float, LocationListener) method

Since I use Fused Location API for location-related stuff, I just set
long minTime = 1 hour,
float minDistance = 1km, in requestLocationUpdates
and this results in very little overhead to my app.

And, of course, don’t forget to locationManager.removeUpdates when you’re done.

Leave a Reply

Your email address will not be published. Required fields are marked *