Detecting the device being plugged in

前端 未结 1 1891
北海茫月
北海茫月 2020-12-01 13:17

I would like to be able to detect whether or not the device is plugged in. I would like to be able to just query that the same way we can do for the connectivity state. Is

相关标签:
1条回答
  • 2020-12-01 13:53

    Apparently the ACTION_BATTERY_CHANGED is a "sticky broadcast" which means you can register for it and receive it any time after it has been broadcast. To get the plugged state you can do something like:

    public void onCreate() {
        BroadcastReceiver receiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
                if (plugged == BatteryManager.BATTERY_PLUGGED_AC) {
                    // on AC power
                } else if (plugged == BatteryManager.BATTERY_PLUGGED_USB) {
                    // on USB power
                } else if (plugged == 0) {
                    // on battery power
                } else {
                    // intent didnt include extra info
                }
            }
        };
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(receiver, filter);
    }
    
    0 讨论(0)
提交回复
热议问题