以编程方式检测Android电源线断开连接(USB或AC充电器)

时间:2016-03-16 09:31:10

标签: android battery disconnected batterymanager

            BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
                int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
                String batteryPercentage = String.valueOf(level);
                Log.d("battery",batteryPercentage);
                boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
                Log.d("ischarging", String.valueOf(isCharging));

                int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
                boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
                boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

                String action = intent.getAction();


                int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
                if (plugged == BatteryManager.BATTERY_PLUGGED_AC && DefaultManager.acChargeConnect && level >= DefaultManager.batteryPercentageTriggerValue) {
                    //do something
                } else if (plugged == BatteryManager.BATTERY_PLUGGED_USB && DefaultManager.usbConnect){
                    //do something
                } else if (plugged == 0) {
                    // on battery power
                } else {
                    // intent didnt include extra info
                }
            }

        };

因此,我希望检测电源线或USB线是否断开连接,并在发生事件时执行某些操作。 我已经阅读了BatteryManager文档并尝试了一些常量,但似乎没有任何工作。我想抓住充电器断开事件做一些事情。任何指针都很受欢迎。谢谢

2 个答案:

答案 0 :(得分:1)

请在此处查看答案,了解正确的行动: How to detect power connected state?

此外,不要创建匿名的BroadcastReceiver,因为它必须在AndroidManifest.xml中注册

答案 1 :(得分:1)

你可以这样做。

Intent intent = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);

        if (plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB) {
            Toast.makeText(getApplicationContext(), "Device is Charging", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "Device not charging", Toast.LENGTH_SHORT).show();
        }