Question

I need to determine whether the power cable (usb cable) is plugged in. The solutions on SO all use a broadcast receiver to receive a power change event. The problem with this approach is that the cable may already be plugged in before my receiver gets registered, in which case no change event will get fired. I need a way to determine whether the cable is plugged in without relying upon a broadcast receiver.

Était-ce utile?

La solution

Check 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;
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top