我想对我的应用中的充电状态作出反应。
我在onCreate()
中注册了接收器registerReceiver(receiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
接收器看起来像那样:
private BroadcastReceiver receiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
plugged= intent.getIntExtra(BatteryManager.EXTRA_PLUGGED,0);
String test = Integer.valueOf(plugged).toString();
Toast.makeText(getApplicationContext(), test,
Toast.LENGTH_LONG).show();
}
};
但即使设备已插入,插入的变量为0.任何想法如何解决?
答案 0 :(得分:0)
您可以尝试使用BatteryManager.EXTRA_STATUS。如果您需要有关我认为的电源类型的更多详细信息,可以使用BatteryManager.EXTRA_PLUGGED。
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent intentResult = registerReceiver(null, filter);
int state = intentResult.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
switch (state) {
case BatteryManager.BATTERY_STATUS_CHARGING:
case BatteryManager.BATTERY_STATUS_FULL:
//charging
break;
default:
//not charging
}