Search code examples
androidgps

Detecting GPS on/off switch in Android phones


I would like to detect when the user changes the GPS settings on or off for an Android phone. Meaning when user switches GPS sattelite on/off or detection via access points etc.


Solution

  • As I have found out the best way to do this is to attach to the

    <action android:name="android.location.PROVIDERS_CHANGED" />
    

    intent.

    For instance:

    <receiver android:name=".gps.GpsLocationReceiver">
            <intent-filter>
                <action android:name="android.location.PROVIDERS_CHANGED" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>
    

    And then in the code:

    public class GpsLocationReceiver extends BroadcastReceiver implements LocationListener 
    ...
    
    @Override
    public void onReceive(Context context, Intent intent)
    {
            if (intent.getAction().matches("android.location.PROVIDERS_CHANGED"))
            { 
                // react on GPS provider change action 
            }
    }