我正在尝试做两份 toast :一份在设备充电时,另一份在不充电时。但是接收方表现得很疯狂,发送了很多 toast ,并导致应用程序崩溃。我找不到问题所在。谢谢!这是主要 Activity 中的接收器:
public class PowerConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
if (isCharging){
Toast.makeText(context, "The device is charging", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "The device is not charging", Toast.LENGTH_SHORT).show();
}
}
}
这是 list :
<receiver android:name=".view.MainActivity$PowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
我找到了一种检查设备是否正在充电的好方法。这是接收器类的代码:
public class PowerConnectionReceiver extends BroadcastReceiver {
public PowerConnectionReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
Toast.makeText(context, "The device is charging", Toast.LENGTH_SHORT).show();
} else {
intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
Toast.makeText(context, "The device is not charging", Toast.LENGTH_SHORT).show();
}
}
}
在 onResume 上注册它:
receiver = new PowerConnectionReceiver();
IntentFilter ifilter = new IntentFilter();
ifilter.addAction(Intent.ACTION_POWER_CONNECTED);
ifilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
registerReceiver(receiver, ifilter);
在暂停时取消注册:
unregisterReceiver(receiver);
工作正常!
我是一名优秀的程序员,十分优秀!