I am trying to register a receiver for the removal of the sdcard, but my receiver is not getting called on removal of the sd card pasting my code here. I am registering the receiver in the oncreate() and unregistering in the ondestroy function. Please let me know if i am doing any mistake.
void registerSDCardStateChangeListener() {
final String MEDIA_REMOVED = "android.intent.action.MEDIA_REMOVED";
final String MEDIA_UNMOUNTED = "android.intent.action.MEDIA_UNMOUNTED";
final String MEDIA_BAD_REMOVAL = "android.intent.action.MEDIA_BAD_REMOVAL";
// final String MEDIA_EJECT = "android.intent.action.MEDIA_EJECT";
final String MEDIA_EJECT = "android.intent.action.MEDIA_SCANNER_FINISHED";
mSDCardStateChangeListener = new BroadcastReceiver() {
@
Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equalsIgnoreCase(MEDIA_REMOVED) || action.equalsIgnoreCase(MEDIA_UNMOUNTED) || action.equalsIgnoreCase(MEDIA_BAD_REMOVAL) || action.equalsIgnoreCase(MEDIA_EJECT)) {
if (mMediaPlayer != null) {
stopPlayBack();
}
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(MEDIA_REMOVED);
filter.addAction(MEDIA_UNMOUNTED);
filter.addAction(MEDIA_BAD_REMOVAL);
filter.addAction(MEDIA_EJECT);
registerReceiver(mSDCardStateChangeListener, filter);
}
Please let me know if anything is wrong in my code.
Try adding this to your intent-filter
filter.addDataScheme("file");
It appears the actions you are trying to catch send the path as the data field of the intent. If that is the case, then your intent filter must have the matching scheme.
Finally, and this is just a suggestion, but I would recommend you use the constants in the Intent class instead of typing out your actions manually. IE, use Intent.ACTION_MEDIA_REMOVED instead of you using the string directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With