ACTION_BATTERY_CHANGED 无效

ACTION_BATTERY_CHANGED doesn't work

我的电池状态应用程序在 Androidstudio 中有一个小问题。我有以下接收器:

<receiver android:name=".PowerConnectionReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="android.intent.action.BATTERY_CHANGED"/>
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
        <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
    </intent-filter>

PowerConnectionReceiver 仅适用于 ACTION_POWER_* 事件。电池更换事件无效

public class PowerConnectionReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {

    if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) 
        Toast.makeText(context, "Loading", Toast.LENGTH_SHORT).show();  

    else if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) 
        Toast.makeText(context, "not loading", Toast.LENGTH_SHORT).show();

    Toast.makeText(context, "test toast", Toast.LENGTH_SHORT).show();
}
}



Intent intent = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

您忘记实例化您的 PowerConnectionReceiver

Intent intent = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

应该是

Intent intent = getApplicationContext().registerReceiver(PowerConnectionReceiver() , new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

更好的办法是保留参考,这样您就可以在 onStop().

中再次注销

有些广播有限制(例如ACTION_BATTERY_CHANGED) 系统发送的不能被静态定义的广播接收器接收。