Detecting Gps On/Off Switch in Android Phones

Detecting GPS on/off switch in Android phones

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

How can I detect if user disable GPS (Android - Play Services)

You can achive this by Setting up a Broadcast Receiver that gets fired whenever the GPS of your device turns on/off

Steps:

1. First of all create a class GPS which extend BroadcastReceiver

public class GPSCheck extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {

LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);

if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{

}
else
{
Toast.makeText(context, "Please switch on the GPS", Toast.LENGTH_LONG).show();
}

}

}

2. And then mention this class in your AndroidManifest.xml file

<receiver android:name="com.yourpackagename.example.GPSCheck" >
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />

<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>

3. Do not forget to add this permission also

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

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

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);
}
}
}


Related Topics



Leave a reply



Submit