简体   繁体   中英

Android BroadcastReceiver can't receive any broadcast events

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());

    }
}

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM