Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gps status enabled/disabled broadcast receiver

Tags:

android

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

like image 772
Dan Dinu Avatar asked Sep 30 '12 22:09

Dan Dinu


1 Answers

There are two ways of registering broadcast receivers in Android:

  1. in the code (your case)
  2. in AndroidManifest.xml

Let me explain the differences.

Case 1 (Broadcast Receiver registered in the code)

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

Case 2 (Broadcast Receiver registered in AndroidManifest.xml)

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.

like image 195
stevo.mit Avatar answered Nov 11 '22 18:11

stevo.mit