Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to detect wheather my android phone is connected via USB or not...for this i′m using this code:

public static boolean isConnected(Context context) {
    intent = context.registerReceiver(null, new IntentFilter("android.hardware.usb.action.USB_STATE"));
    return intent.getExtras().getBoolean("connected");
}

But is there a possibility to explicit know if i am connected to a PC?! Because the Solution i have fires the Event even i connect my phone to a printer or sth else with an USB Port...

I already tried the Solution @nios just posted, but if isCharging and usbCharge booleans are set to true, it′s not guaranted that your are connected to a PC...Even if you are connected to a Printer both booleans will bet set to true...Thats my Problem

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
571 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use this IntentFilter :

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                 status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

If isCharging and usbCharge booleans are set to true, you are connected to a PC via USB.

Hope this helps.

Found on http://developer.android.com/training/monitoring-device-state/battery-monitoring.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...