Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Detecting USB

Tags:

android

usb

Is there any way to know(programmatically) in your Activity/Application that the user has connected your phone to PC through USB?

like image 304
AjOnFire Avatar asked Jan 05 '11 04:01

AjOnFire


People also ask

Why is my USB not showing up on my Android phone?

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.

Why is my phone not recognizing my USB device?

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.


2 Answers

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

like image 84
Faeriol Avatar answered Oct 21 '22 03:10

Faeriol


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);

like image 20
AjOnFire Avatar answered Oct 21 '22 03:10

AjOnFire