以编程方式检测 Android 中的电源线何时断开连接(USB 或交流充电器)

Detect when Power Cable disconnected(USB or AC Charger) in Android programmatically

            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 文档并尝试了那里提到的一些常量,但似乎没有任何效果。我想捕获充电器断开连接的事件来做点什么。任何指针表示赞赏。谢谢

请在此处查看答案以了解要收听的正确操作: How to detect power connected state?

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

中注册

你可以像这样简单地做。

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();
        }