Android: Detect When SD Card Mounted as Disk Drive to a Computer

Heshan Perera picture Heshan Perera · Apr 10, 2012 · Viewed 8.3k times · Source

I am writing an application that needs to detect when the SD card is mounted as a disk drive to a computer via USB or when it has been manually removed. I tried using a broadcast receiver for this purpose, but the onReceive is not getting called. My code is as follows.

IntentFilter filter2 = new IntentFilter();
        //filter2.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        filter2.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        filter2.addAction(Intent.ACTION_MEDIA_SHARED);
        filter2.addAction(Intent.ACTION_MEDIA_REMOVED);
        filter2.addAction(Intent.ACTION_MEDIA_MOUNTED);

        registerReceiver(new CustomBroadcastReceiver(), filter2);

My broadcast receiver is as follows...

public class CustomBroadcastReceiver extends BroadcastReceiver{

    public CustomBroadcastReceiver(){

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if(action.equals(Intent.ACTION_MEDIA_UNMOUNTED) || action.equals(Intent.ACTION_MEDIA_SHARED) || action.equals(Intent.ACTION_MEDIA_REMOVED)){
            HardwareManager.IS_MEDIA_MOUNTED = false;
        }else if(action.equals(Intent.ACTION_MEDIA_MOUNTED)){
            HardwareManager.IS_MEDIA_MOUNTED = true;
        }else if(action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)){
            HardwareManager.IN_AIRPLANE_MODE = intent.getBooleanExtra("state", false);
        }
    }

}

The onReceive method does not fire when I connect as a disk drive via USB.

What am I doing wrong ?

Answer

Massycat picture Massycat · May 2, 2012

You have to add the "file" scheme (addDataScheme("file")) in order for the IntentFilter to match the broadcast ACTION_MEDIA_* action intents.

The ACTION_MEDIA_* intents have the path to the mount point in Intent.mData field (see Intent docs) but an IntentFilter with no schemes set will only match an intent if it includes no data (see IntentFilter docs).