Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Battery broadcast receiver declared in manifest file does not work?

There are two ways to make a broadcast receiver known to the system: One declares it in the manifest file with this element. The other is to create the receiver dynamically in java code.

Now, the receiver has been created dynamically in java code and it does work normally.But why the first way "Declare in the manifest file" failed?

Is there anyone to success?

Thanks.

AndroidManifest.xml

<receiver android:name="pj.batteryinfo.BatteryReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BATTERY_CHANGED"></action>
    </intent-filter>
</receiver>
like image 834
Sodino Avatar asked Feb 03 '12 02:02

Sodino


People also ask

How do you check broadcast receiver is registered or not in Android?

A simple solution to this problem is to call the registerReceiver() in your Custom Application Class. This will ensure that your Broadcast receiver will be called only one in your entire Application lifecycle.

Does broadcast receiver work in background?

If you want a background receiver, you need to register it inside the AndroidManifest (with intent filter), add an IntentService and start it when you receive a broadcast in the receiver.


1 Answers

For some actions, you could only declare the BroadcastReceiver in Java code. This happens to the BATTERY_CHANGED action and SCREEN_ON,SCREEN_OFF so far as I know.

When you declare a BroadcastReceiver in the Manifest.xml file, no matter whether your app is running or not, the BroadcastReceiver will be awaken and thus the onReceive method will be called.

Why?I think this is because the BATTERY_CHANGED action is very common to take place and if you can declare it in the Manifest, the system will often send a lot of broadcasts and thus consumes battery dramatically;however, when you declare it in the code, the broadcastReceiver will only be effective when the activity is running and thus avoid extreme battery consumption. To save battery, Android doesn't allow such actions to be registered in the file.

This is just my guess. I didn't see any official explanations on this. As a developer, I just memorize such actions, rather than the reasons behind them.

like image 68
Huang Avatar answered Oct 06 '22 00:10

Huang