android USB connection charging signals

丶灬走出姿态 提交于 2019-12-12 04:35:38

问题


How can I check the USB socket is plugged or not (Charging with AC / USB)? (android version 2.1 / 2.2)

I am writing a wireless charging application that I want to get different types of charging signals ( wireless , AC charging / USB ). I used broadcastReceiver to get the charging signal and found that using wireless charging and AC charging return the same signal (AC charging). To distinguish wireless charging and AC charging, I want to detect the USB socket is plugged or not. I try to use Intent.ACTION_UMS_CONNECTED to detect the USB signal but it also return SD card.

How can I check the USB socket is plugged or not (Charging with AC / USB)? (android version 2.1 / 2.2)


回答1:


To check device charging with AC / USB, Lets try this,

Call registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)). This will return an Intent that has extras defined on BatteryManager to let you know if it is plugged in or not.

Something with code,

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



回答2:


As of Jellybean 4.2 there is BatterManager.BATTERY_PLUGGED_WIRELESS



来源:https://stackoverflow.com/questions/8411846/android-usb-connection-charging-signals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!