您的位置:首页 > 移动开发 > Android开发

Android 获取手机充电状态

2017-11-04 14:45 686 查看

通过注册广播

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, "action is " + action);
switch (action) {
case Intent.ACTION_POWER_CONNECTED:
case "test.charge":
mCharge = true;
break;

case Intent.ACTION_POWER_DISCONNECTED:
case "test.uncharge":
mCharge = false;
break;

case Intent.ACTION_BATTERY_CHANGED:
mBatteryPercent = intent.getIntExtra("level", 100);
int state = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
Log.d(TAG, " battery state is " + state);
mCharge = (state == BatteryManager.BATTERY_STATUS_FULL) || (state == BatteryManager.BATTERY_STATUS_CHARGING);

mLowerPower = mBatteryPercent <= mLowBatteryWarningPercent ? true : false;
/* when power charging ,the lowerpower flag false*/
if (mCharge) {
mLowerPower = false;
}
break;


通过注册

Intent.ACTION_POWER_CONNECTED

Intent.ACTION_POWER_DISCONNECTED

来获取手机插拔数据线状态。

通过注册

Intent.ACTION_BATTERY_CHANGED

来监听电量变化

case Intent.ACTION_BATTERY_CHANGED:
mBatteryPercent = intent.getIntExtra("level", 100);
int state = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
Log.d(TAG, " battery state is " + state);
mCharge = (state == BatteryManager.BATTERY_STATUS_FULL) || (state == BatteryManager.BATTERY_STATUS_CHARGING);


通过

int state = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

来得到state 状态

state == BatteryManager.BATTERY_STATUS_CHARGING 判断是否充电状态。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: