Search code examples
androidbroadcastreceiver

Android: Detect USB flash drive plugged in


Is there a way to detect when a USB flash drive is plugged into an Android device? I'm able to detect an SD card using a broadcast receiver, but it doesn't work for USB. I'd like to avoid polling.

code to register receiver:

private void RegisterUpdateReceiver()
{
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.intent.action.MEDIA_MOUNTED");
    intentFilter.addDataScheme("file");
    myReceiver = new MyReceiver();
    this.registerReceiver(myReceiver, intentFilter);
}

receiver code:

public class MyReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();
        if (action.equals("android.intent.action.MEDIA_MOUNTED")) 
        {
            // react to event
        }
}

Solution

  • Android, at the SDK level, has no concept of USB drives. There are no rules for where they should be mounted, broadcasts for when they appear/disappear, etc. Perhaps some standardization in this area will come in future Android releases, but it is not there today.