Is there any way to know(programmatically) in your Activity/Application that the user has connected your phone to PC through USB?
Restart Your Mobile Device One easy fix for a USB device that's not recognized by your Android phone is to restart your phone. This is one of the go-to solutions recommended by Android experts whenever you're encountering any issue with your phone.
If your device is not correctly detected in RAD Studio or in the system Device Manager, check the following: Ensure that your Android device is unlocked and not sleeping while connected via USB. Set the appropriate option in Settings or Developer Options. Make sure your Android device is enabled for USB debugging.
Some people suggested using UMS_CONNECTED
which is deprecated as of recent version of Android
The other problem with that is that it does not work with MTP enabled devices
Others suggested the use of the BatteryManager
, more precisely ACTION_BATTERY_CHANGED
as well as BATTERY_PLUGGED_AC
and BATTERY_PLUGGED_USB
This is perfect if you want to detect the Battery or Charging status of the device, but is not a really good indicator of a USB connection.
Using the battery manager is prone to failure on older android tablets such as the XOOM, the ICONIA tab A510, and the older Asus tablets.
To purely detect that the device was plugged on a PC you can:
Use android.hardware.usb.action.USB_STATE
and connected
in place of the BatteryManager
stuff
Code sample
public static boolean isConnected(Context context) {
intent = context.registerReceiver(null, new IntentFilter("android.hardware.usb.action.USB_STATE"));
return intent.getExtras().getBoolean("connected");
}
Hope this helps
Was able to detect USB connection by registering a broadcast receiver by following,
IntentFilter mIntentFilter = new IntentFilter(Intent.ACTION_UMS_CONNECTED); BroadcastReceiver bd = new intentReceiver(); registerReceiver(bd, mIntentFilter);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With