Arun kumar Arun kumar - 1 month ago 58
Android Question

Android - turn GPS on or off programmatically

Why we need to go setting for on/off GPS on the other hand we can on/off WIFI and Bluetooth programmatically without move to settings.
Android Guidelines have changed above version 4.0. You cannot change GPS off on programmatically for versions above 4.0.

Answer

There used to be a way to enable / disable GPS programmatically by sending the android.location.GPS_ENABLED_CHANGE broadcast:

Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", enabled);
sendBroadcast(intent);

where enabled would be true or false respectively.

If you take a look at this bug report, this hack was subverted in Android 4.4. It still works on older OS versions.

Now the answer to your question

Why we need to go setting for on/off GPS on the other hand we can on/off WIFI and Bluetooth programmatically without move to settings ?

Android's GPS technology periodically sends location data to Google even when no third-party apps are actually using the GPS function. In many Western countries this is seen as a major violation of privacy. That's why Google made it mandatory to get the user's consent before using the GPS function. The following dialog is seen whenever the user turns GPS on:

GPS user permission

And hence it is no longer possible to programmatically change the GPS settings, as by necessity it requires the user's permission. What the programmer can do is direct the user to the GPS settings by calling

startActivity(context, new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));

and let the user make a choice.

As an interesting point, if you try sending the GPS_ENABLED_CHANGE broadcast on the new OS versions, you get a

java.lang.SecurityException: Permission Denial: 
    not allowed to send broadcast android.location.GPS_ENABLED_CHANGE

error. As you can see, its a SecurityException with a permission denial message.

Comments