我的电池状态应用程序在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));发布于 2018-03-25 14:06:46
您忘记实例化您的PowerConnectionReceiver。
Intent intent = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));应该是
Intent intent = getApplicationContext().registerReceiver(PowerConnectionReceiver() , new IntentFilter(Intent.ACTION_BATTERY_CHANGED));更好的做法是保留一个引用,这样您就可以在onStop()中再次取消注册。
发布于 2021-08-25 12:08:38
有一个限制,即由系统发送的某些广播(例如ACTION_BATTERY_CHANGED)不能由静态定义的广播接收器接收。
https://stackoverflow.com/questions/49476650
复制相似问题