Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not getting the SD Card related intents to my broadcast receiver

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.

like image 923
Suman Avatar asked Jun 09 '11 13:06

Suman


1 Answers

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.

like image 80
Justin Breitfeller Avatar answered Nov 15 '22 21:11

Justin Breitfeller