How to detect power connected state?

前端 未结 5 1418
庸人自扰
庸人自扰 2020-11-30 13:24

Is there an easy way to be notified when USB or AC power is connected to an Android phone?

5条回答
  •  旧巷少年郎
    2020-11-30 14:12

    another way is using battery manager. this i usable for api>=21

    public class PowerUtil {
        public static boolean isConnected(Context context) {
            Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
            return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
        }
    }
    

提交回复
热议问题