【问题标题】:Determine if power/usb cable is plugged in Android device [duplicate]确定电源/USB线是否插入Android设备[重复]
【发布时间】:2013-09-24 13:07:08
【问题描述】:
我需要判断电源线(usb cable)是否插上。SO上的解决方案都是使用广播接收器来接收电源变化事件。这种方法的问题是在我的接收器注册之前电缆可能已经插入,在这种情况下不会触发任何更改事件。我需要一种方法来确定电缆是否已插入而不依赖广播接收器。
【问题讨论】:
标签:
android
power-management
【解决方案1】:
检查this link。
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;
}
}