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

4

2 回答 2

1

请参阅此处的答案以了解要收听的正确操作: 如何检测电源连接状态?

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

于 2016-03-16T09:51:04.357 回答
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();
        }
于 2016-03-16T10:31:56.827 回答