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

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

java - Detect USB Connection and check if it is a PC

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...