Gps status enabled/disabled broadcast receiver

后端 未结 1 674
时光说笑
时光说笑 2020-12-17 10:10

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

相关标签:
1条回答
  • 2020-12-17 10:25

    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.

    0 讨论(0)
提交回复
热议问题