Wednesday, April 11, 2012

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

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 ?





No comments:

Post a Comment