Android: Detecting USB

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


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


This works for me.

Add this on your AndroidManifest.xml

        <receiver android:name=".PlugInControlReceiver">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
                <action android:name="android.hardware.usb.action.USB_STATE" />
            </intent-filter>
        </receiver>

And Create your BroadcastReceiver.

public class PlugInControlReceiver extends BroadcastReceiver {

    @Override public void onReceive(final Context context, Intent intent) {

        String action = intent.getAction();
        Log.v("PlugInControlReceiver","action: "+action);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){

            if(action.equals("android.hardware.usb.action.USB_STATE")) {

                if(intent.getExtras().getBoolean("connected")){

                    Toast.makeText(context, "USB Connected", Toast.LENGTH_SHORT).show();
                }else{

                    Toast.makeText(context, "USB Disconnected", Toast.LENGTH_SHORT).show();
                }
            }
        } else {
            if(action.equals(Intent.ACTION_POWER_CONNECTED)) {

                Toast.makeText(context, "USB Connected", Toast.LENGTH_SHORT).show();
            }
            else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)) {

                Toast.makeText(context, "USB Disconnected", Toast.LENGTH_SHORT).show();
            }
        }  
   }      
}

Tags:

Android

Usb