27

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?

0

11 Answers 11

37

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.

7
  • The check in onReceive can even be simplified by not checking for a regex: LocationManager.PROVIDERS_CHANGED_ACTION.equals(intent.getAction())
    – droide_91
    Jun 22, 2018 at 9:08
  • Do you mean that that check should be removed or improved?
    – sud007
    Jun 23, 2018 at 8:48
  • It can be changed by not using the hard-coded string "android.location.PROVIDERS_CHANGED", but LocationManager.PROVIDERS_CHANGED_ACTION.
    – droide_91
    Jun 24, 2018 at 12:23
  • 2
    @sud007: Going forward, app no longer going to listen broadcast receiver unless it is whitelisted. So now we need to change our receiver from manifest declaration to java/kotlin declaration as per the answer. Now if app is killed and I turn on GPS I have no other way by which my app could know that GPS is turned on/off, here comes my concern how my app is going to listen if I follow mentioned approach?
    – Rohit
    Oct 23, 2018 at 13:38
  • 1
    @Rohit thanks for pointing that out! As this answer was prop0sed long back. It would be great if you were able to deduce some other solutions as per updated documentation. I will surely try to update the solution very soon. Thanks!
    – sud007
    Feb 7, 2019 at 3:19
27

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

1
  • 7
    So from Nougat onwards addGpsStatusListener was deprecated in API level 24. use registerGnssStatusCallback(GnssStatus.Callback) instead. as per the Android docs here
    – sud007
    Sep 26, 2016 at 10:16
9

Listen to 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 activity's onPause() method:

mActivity.unregisterReceiver(gpsSwitchStateReceiver);
1
  • i run this code and when i turn on gps manually it works otherwise it dont show anything if gps is off can you know why? i use same code. Jan 6, 2021 at 14:40
5

In Kotlin try this:

Add a class which extends BroadcastReceiver:

class GPSCheck(private val locationCallBack: LocationCallBack) :
    BroadcastReceiver() {
    interface LocationCallBack {
        fun turnedOn()
        fun turnedOff()
    }

    override fun onReceive(context: Context, intent: Intent) {
        val locationManager =
            context.getSystemService(LOCATION_SERVICE) as LocationManager
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) locationCallBack.turnedOn() else locationCallBack.turnedOff()
    }

}

Then as an example use it this way:

class MainActivity :AppCompatActivity(){

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        registerReceiver(GPSCheck(object : GPSCheck.LocationCallBack {
            override fun turnedOn() {
                Log.d("GpsReceiver", "is turned on")
            }

            override fun turnedOff() {
                Log.d("GpsReceiver", "is turned off")
            }
        }), IntentFilter(LocationManager.MODE_CHANGED_ACTION))
    }}
3

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.

2
  • 1
    I want to make the gps state to previous state whenever user changes it.I need something like broadcastreceiver for listening android.net.conn.CONNECTIVITY_CHANGE
    – Devu Soman
    Apr 3, 2013 at 4:26
  • 3
    Then restructure your question because thats not what you're asking. You're asking about RESTRICTING change not listen for it.
    – JoxTraex
    Apr 3, 2013 at 4:28
2

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.

0
2

We can use LocationListener to know when GPS is on and when it is off.

class HomeActivity : AppCompatActivity() {
    private var locManager: LocationManager? = null
    private val locListener: LocationListener =
        object : LocationListener {
            override fun onLocationChanged(loc: Location) {
            }

            override fun onProviderEnabled(provider: String) {
                Log.d("abc", "enable")
            }

            override fun onProviderDisabled(provider: String) {
                Log.d("abc", "disable")
            }

            override fun onStatusChanged(
                provider: String,
                status: Int,
                extras: Bundle
            ) {
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        locManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
    }

    override fun onResume() {
        super.onResume()
        startRequestingLocation()
    }

    override fun onStop() {
        super.onStop()
        try {
            locManager!!.removeUpdates(locListener)
        } catch (e: SecurityException) {
        }
    }

    private fun startRequestingLocation() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
            checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                PERMISSION_REQUEST
            )
            return
        }
        locManager!!.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0f, locListener)
    }

    companion object {
        private const val PERMISSION_REQUEST = 1
    }
}

See this project for more details: https://github.com/pR0Ps/LocationShare

1

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.

0

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

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 !

-1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.