Android: ACTION_BATTERY_LOW not triggered in emulator. Receiver registered in code, not manifest

喜你入骨 提交于 2019-12-04 06:18:54

make sure: 1. you are setting the "Charger connection" to "NONE" 2. That battery status is "Discharging"

You can add the following code in your manifest.

<receiver android:name=".yourpackage.BroadCastNotifier" >
  <intent-filter>
    <action android:name="android.intent.action.BATTERY_LOW" />
  </intent-filter>
</receiver>

In your BroadCastNotifier Class

package yourpackage;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BroadCastNotifier extends BroadcastReceiver {
    private final static String TAG = "BroadCastNotifier"; 
    @Override
    public void onReceive(Context context, Intent intent) {
        String intentAction = intent.getAction();

        if(Intent.ACTION_BATTERY_LOW.equalsIgnoreCase(intentAction)){
            Log.e(TAG, "GOT LOW BATTERY WARNING");          
        }
    }

}

You will recieve the log message GOT LOW BATTERY WARNING when your battery is low, also try this in your device.

Although the above code might work the best way is not to use BroadCast for such actions, you can monitor the battery level as described here. You can determine your battery with the code below which is way easier.

int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

float batteryPct = level / (float)scale; 

The key is to disable charging with the telnet command

power ac off

If you then set the battery level to a low capacity

power capacity 1

the intent will be triggered

Mr_and_Mrs_D

You can register ACTION_BATTERY_LOW in the manifest - see my detailed answer here - you can't register ACTION_BATTERY_CHANGED in the manifest.

The reason you do not receive it is probably you forgot to declare your RECEIVER in the manifest

Also if I have to call registerReceiver() inside an activity and I do not call unregisterReceiver on onStop or onDestroy, is it okay?

No. You should register in onResume and unregister on onPause ALWAYS - after onPause is called your receiver WON'T receive anyway

If not okay, how will I register for a receiver to receive system intents even when my app is not in foreground? (Apart from using manifest).

Only in manifest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!