I m trying to register a broadcast receiver to receive updates when gps status is changed.
However, my GpsChangeReceiver onReceive method doesn't seem to be called when gps status is changed from enabled to disabled or vice-versa.
First of all, i'm registering the reciever:
GpsChangeReceiver m_gpsChangeReceiver = new GpsChangeReceiver();
this.registerReceiver(m_gpsChangeReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
Then, I have my GPS Receiver
public class GpsChangeReceiver extends BroadcastReceiver
{
@Override
public void onReceive( Context context, Intent intent )
{
final LocationManager manager = (LocationManager) context.getSystemService( Context.LOCATION_SERVICE );
if (manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
//do something
}
else
{
//do something else
}
}
}
Finally, my manifest contains:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Can anyone see why the gps receiver is never called when I modify its status from the phone's settings??
There are two ways of registering broadcast receivers in Android:
Let me explain the differences.
You will only receive broadcasts as long as context where you registered your receiver is alive. So when activity or application is killed (depending where you registered your receiver) you won't receive broadcasts anymore.
I guess you registered broadcast receiver in the activity context which is not very good approach. If you want to register broadcast receiver for your application context you can do something like this:
getApplicationContext().registerReceiver(m_gpsChangeReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
You will receive broadcasts even when your application is killed (system will wake your application up). This is right approach when you want to receive broadcasts no matter if your app is running.
Add this receiver to your AndroidManifest.xml:
<receiver android:name="com.yourpackage.NameOfYourBroadcastReceiver">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
</intent-filter>
</receiver>
EDIT: Some special broadcasts (i.e. SCREEN_ON or SCREEN_OFF) must be registered in code (case 1) otherwise they won't be delivered to your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With