Android 获取手机充电状态

来源:互联网 发布:php博客系统实战开发 编辑:程序博客网 时间:2024/04/28 02:37

通过注册广播

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 判断是否充电状态。

原创粉丝点击