In a button click, I want to check any USB is connected to the device or not. If connected then some action(may be a toast).When a button is clicked a broadcast for checking if USB is connected or not.
Asked
Active
Viewed 246 times
1 Answers
1
I am not sure about all the censorious but here how you test if your device is charging:
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;
}
}
Found at this question.
Edit: Using UsbManager.getDeviceList you get all the connected devices. So if size is 0 no USB is connected.

Community
- 1
- 1

Ilya Gazman
- 31,250
- 24
- 137
- 216
-
@Jerry See my edit. Found it using a hint from Dharmesh answer – Ilya Gazman Dec 31 '13 at 12:11