Home » Android » Android BroadcastReceiver can't receive any broadcast events

Android BroadcastReceiver can't receive any broadcast events

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have created a BroadcastReceiver to detect SDCard mount and unmount
event, however, I am not able to receive any events at all:
here’s the AndroidManifest.xml:

<receiver android:enabled="true" android:label="SDCardMountReceiver" android:exported="true" android:name="xxx.broadcasts.SDCardBroadcastReceiver">
    <intent-filter>
        <action android:name="android.content.Intent.ACTION_MEDIA_MOUNTED"></action>
        <!-- or <action android:name="android.content.Intent.ACTION_MEDIA_UNMOUNTED" />--></intent-filter>
</receiver>

And the SDCardMountReceiver class:

public class SDCardBroadcastReceiver extends BroadcastReceiver {
    public SDCardBroadcastReceiver() {
        super();
        System.err.println("constructor");
    }

    public void onReceive(Context context, Intent intent) {
        Log.d("SDCardBroadCastReceiver", "receive " + intent.getAction());
        System.err.println("jonathan receive " + intent.getAction());

    }
}
How to&Answers:

The Intent javadoc specifies a different action:name value.
Use “android.intent.action.MEDIA_MOUNTED” instead of “android.content.Intent.ACTION_MEDIA_MOUNTED”

Answer:

You also need to set the data scheme to “file”.

   <intent-filter>
     <action android:name="android.intent.action.MEDIA_MOUNTED" />
     <data android:scheme="file" /> 
   </intent-filter>

Reference: android-developers thread

Answer:

If you register a broadcast receiver programmatically, you must also set the scheme to “file”.

IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addDataScheme("file");
mContext.registerReceiver(mExternalStorageReceiver, filter);