电池电量变化时不调用 BroadcastReceiver 的 onReceive

BroadcastReceiver's onReceive not called when battery level changes

我有带 BATTERY_CHANGED IntentFilter 的 BroadcastReceiver。当我尝试发送广播时,onReceive 没有调用。怎么了?这是我在清单中的接收器描述

<receiver android:name=".receivers.BatteryReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BATTERY_CHANGED"/>
        </intent-filter>
    </receiver>

我的广播接收器

public class BatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Log.d("tag", "onRecv");
    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    if (level != -1 && scale != -1) {
        float batteryPct = level / (float) scale;
        if (batteryPct < 30) {
            NotificationBuilder.notifyWithActions(context, R.drawable.ic_info_black_24dp,
                    context.getResources().getString(R.string.app_name),
                    context.getResources().getString(R.string.battery),
                    context.getResources().getInteger(R.integer.battery));
        }
    }
}`}

我试试

LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(Intent.ACTION_BATTERY_CHANGED));

您可以通过 adb 发送虚假系统广播:

adb shell am broadcast "intent:#Intent;action=android.intent.action.BATTERY_CHANGED;i.status=5;i.voltage=4155;i.level=100;end"

我正在尝试使用这种广播来检测电池电量,但它不起作用。 然后对于这个任务,我使用在 MainActivity 中创建广播并使用操作 Intent.ACTION_BATTERY_CHANGED 注册它并且不需要在 manifest.xml 中注册接收器并且它工作得更好。

只要电池电量发生变化,就会执行 onReceive(Context c, Intent i) 块中的广播调用和任务。

public class MainActivity extends Activity {
private BroadcastReceiver BatteryReceiver = new BroadcastReceiver() {
    public void onReceive(Context c, Intent i) {

        // Getting level of Battery   
        int level = i.getIntExtra("level", 0);
        Toast.makeText(MainActivity.this,"Battery Level:" +Integer.toString(level) + "%",
                    Toast.LENGTH_SHORT).show();
        // For any Level you have to check here.
        if (level == 100) {
            Toast.makeText(MainActivity.this, "Battery Full",
                    Toast.LENGTH_SHORT).show();
        }

    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Register receiver with Action and no need to define Broadcast in manifest.xml
    registerReceiver(BatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
   }
}