广播接收器-监视电池电量和充电状态 [英] Broadcast receiver - monitoring the Battery Level and Charging State
本文介绍了广播接收器-监视电池电量和充电状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试进行两次祝酒:一次在设备充电时,一次在不充电时。
但是接收方表现得很疯狂,发送了很多吐司,并使应用程序崩溃了。
我找不到问题。
thnx!
这是主要活动中的接收方:
I am trying to make two toasts: one when the device is charging, and one when it`s not. But the receiver acting crazy, sending many toasts, and crashing the app. I can not find the problem. thnx! This is the receiver in Main 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();
}
}
}
这是清单:
<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>
推荐答案
我找到了一种检查设备是否可用的好方法充电与否。
这是接收器类的代码:
I found a great way to check if the device is charging, or not. Here is the code of the receiver class:
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上注册:
Registering it on onResume:
receiver = new PowerConnectionReceiver();
IntentFilter ifilter = new IntentFilter();
ifilter.addAction(Intent.ACTION_POWER_CONNECTED);
ifilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
registerReceiver(receiver, ifilter);
在onPause上未注册:
Unregistered on onPause:
unregisterReceiver(receiver);
工作正常!
这篇关于广播接收器-监视电池电量和充电状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文