I can't receive broadcast on battery state change?

前端 未结 3 1430
野趣味
野趣味 2020-12-06 17:07

I am having the exact same problem as this post: Battery broadcast receiver doesn't work. But it seems no one has answered that question.

Here is my BroadcastRec

相关标签:
3条回答
  • 2020-12-06 17:29

    Make sure you have the battery receiver class not as a subclass of another one but as a seperate class in your project.

    Also try using Context.registerReceiver() method explicitly in your code and do not forget to unregister it: http://developer.android.com/reference/android/content/Context.html#registerReceiver%28android.content.BroadcastReceiver,%20android.content.IntentFilter%29

    0 讨论(0)
  • 2020-12-06 17:32

    From the documentation for ACTION_BATTERY_CHANGED:

    You can not receive this through components declared in manifests, only by explicitly registering for it with Context.registerReceiver(). See ACTION_BATTERY_LOW, ACTION_BATTERY_OKAY, ACTION_POWER_CONNECTED, and ACTION_POWER_DISCONNECTED for distinct battery-related broadcasts that are sent and can be received through manifest receivers.

    There you have it: you must explicitly register for it from your Java code.

    0 讨论(0)
  • 2020-12-06 17:34

    I just followed the Android Developer Guide's on Monitoring the Battery Level and Charging State and had immediate success. If BatteryLevelReceiver is it's own class then I would recommend:

    <receiver android:name=".BatteryLevelReceiver">
        <intent-filter android:priority="900">
           <action android:name="android.intent.action.BATTERY_LOW" />
           <action android:name="android.intent.action.BATTERY_CHANGED" />
        </intent-filter>
    </receiver>
    

    Addition

    I'm willing to guess that you wrote BatteryLevelReceiver as a nested class in ReceversAndServices. According to Receiver as inner class in Android, you cannot do that with non-static classes. You could make BatteryLevelReceiver a static class and register the receiver in onResume(), but then your app will need to be running to catch the events... Move your receiver to a separate class and register these Intents:

    <receiver android:name=".BatteryLevelReceiver">
        <intent-filter android:priority="900">
           <action android:name="android.intent.action.BATTERY_LOW" />
           <action android:name="android.intent.action.BATTERY_OKAY" />
           <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
           <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
        </intent-filter>
    </receiver>
    

    (Not BATTERY_CHANGED as Darshan Computing pointed out.)

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