How to trigger broadcast receiver when gps is turn on/off?
Asked Answered
E

5

45
public class BootReceiver extends BroadcastReceiver  {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
            Toast.makeText(context, "in android.location.PROVIDERS_CHANGED",
                Toast.LENGTH_SHORT).show();
            Intent pushIntent = new Intent(context, LocalService.class);
            context.startService(pushIntent);
        } else {
            Toast.makeText(context, "not in android.location.PROVIDERS_CHANGED",
                Toast.LENGTH_SHORT).show();
            Intent pushIntent = new Intent(context, LocalService.class);
            context.startService(pushIntent);
        }
    }

    @Override
    public void onLocationChanged(Location arg0) {

    }
}

In my app , i need to trigger broadcast receiver when gps is turn on/off. look into the matter and suggest best one to implement in app.

Ecclesiastic answered 19/12, 2013 at 4:42 Comment(1)
Are you trying to listen for setting of Location mode: 'Device only (Use GPS to determine your location)'?Manrope
O
76

This is useful when user want to trigger any action on turn On/Off location provides

You should add this action in manifest

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

and after add this action you can trigger your broadcast receiver

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

And in your BroadcastReceiver class you have to implement LocationListener in that class which is given following below..

public class GpsLocationReceiver extends BroadcastReceiver {        
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
            Toast.makeText(context, "in android.location.PROVIDERS_CHANGED",
            Toast.LENGTH_SHORT).show();
            Intent pushIntent = new Intent(context, LocalService.class);
            context.startService(pushIntent);
        }
    }
}
Oddity answered 19/12, 2013 at 4:59 Comment(6)
Do you have any solution for screen rotation broadcast receiver???????? please helpChumley
Why do i need to implement LocationListener here?Beria
@Kartihkraj... No there is no need to implement LocationListener here.. I have edited this now.Oddity
@AndroidGuru How does this code tell you if Location mode is on/off?Manrope
Where to add <action android:name="android.location.PROVIDERS_CHANGED" /> other than Intent filter of broadcast receiverSilverstein
How to know location turned OFF/ON ?Stepaniestepbrother
T
42

I want to add @Deepak Gupta answer. I want to add code for how to register a dynamic brodacsast receiver in your fragment or activity when GPS status changed.

Register your broadcast receiver as below in your activity or fragment.

private BroadcastReceiver gpsReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().matches(LocationManager.PROVIDERS_CHANGED_ACTION)) {
            //Do your stuff on GPS status change
        }
    }
};

For fragment:

getContext().registerReceiver(gpsReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));

For activity:

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

This can be used any place where you have access to a Context, not just inside an activity or fragment. I hope its helps.

Tuberculate answered 6/7, 2016 at 14:40 Comment(7)
No need to hard-code the action string. Instead use ...matches(LocationManager.PROVIDERS_CHANGED_ACTION) and ...new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION)Josephinajosephine
Thanks @tir38, I have updated my answer with LocationManager.PROVIDERS_CHANGED_ACTIONTuberculate
What is registerReceiver? @TuberculateCatoptrics
It is an activity method which use to register BroadcastReceiver. Check developer.android.com/reference/android/content/Context.htmlTuberculate
Is this still working?, I can't seems to be getting Broadcast on LocationManager.PROVIDERS_CHANGED_ACTIONInterchangeable
Using this We cannot know whether it was turned on or offMurielmurielle
How to know location turned OFF/ON ?Stepaniestepbrother
M
14

You can try this code, as user @DanielNugent pointed out:

    ContentResolver contentResolver = getContext().getContentResolver();
    // Find out what the settings say about which providers are enabled
    int mode = Settings.Secure.getInt(
            contentResolver, Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF);

    if (mode != Settings.Secure.LOCATION_MODE_OFF) {
      if (mode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY) {
        locationMode = "High accuracy. Uses GPS, Wi-Fi, and mobile networks to determine location";
      } else if (mode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY) {
          locationMode = "Device only. Uses GPS to determine location";
      } else if (mode == Settings.Secure.LOCATION_MODE_BATTERY_SAVING) {
          locationMode = "Battery saving. Uses Wi-Fi and mobile networks to determine location";
      }
    }
Manrope answered 20/3, 2015 at 20:49 Comment(2)
Your answer works great, but it works only for Android API version 19 and above. Is there a way for versions lower than 19?Gearard
That setting constants were deprecated in API level 28.Biauriculate
E
0

Working solution after Android location modes are introduced in Android

We can check with location mode for more accurate

private boolean isGpsEnabled(Context context) {
            ContentResolver contentResolver = getContext().getContentResolver();
            // Find out what the settings say about which providers are enabled
            //  String locationMode = "Settings.Secure.LOCATION_MODE_OFF";
            int mode = Settings.Secure.getInt(
                    contentResolver, Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF);
            if (mode != Settings.Secure.LOCATION_MODE_OFF) {
                return true;
               /* if (mode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY) {
                    locationMode = "High accuracy. Uses GPS, Wi-Fi, and mobile networks to determine location";
                } else if (mode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY) {
                    locationMode = "Device only. Uses GPS to determine location";
                } else if (mode == Settings.Secure.LOCATION_MODE_BATTERY_SAVING) {
                    locationMode = "Battery saving. Uses Wi-Fi and mobile networks to determine location";
                }*/
            } else {
                return false;
            }
        }
Embrocate answered 9/2, 2019 at 6:31 Comment(0)
D
-3

you can try this

Manifest

<receiver android:name=".MyReceiver">
        <intent-filter>
            <action android:name="android.location.GPS_ENABLED_CHANGE" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

MyReceiver

if (intent.getAction().matches("android.location.GPS_ENABLED_CHANGE"))
    {
        boolean enabled = intent.getBooleanExtra("enabled",false);

        Toast.makeText(context, "GPS : " + enabled,
                Toast.LENGTH_SHORT).show();
    }
Diadromous answered 9/12, 2017 at 8:34 Comment(1)
Intent is always null. Dose not contain anything like enabled.Titular

© 2022 - 2024 — McMap. All rights reserved.