Recently, the project needs to monitor the insertion and removal of the SD card. Many things are not mentioned when searching for broadcasts on the Internet. I will record these items for future use.
1. If a single activity listens for broadcast, use the following code to register broadcast in the oncreate method of the activity.
IntentFilter iFilter = new IntentFilter();iFilter.addAction(Intent.ACTION_MEDIA_EJECT);iFilter.addDataScheme("file");registerReceiver(mBroadcastReceiver , iFilter);
2. If the whole program listens for broadcasts, register broadcasts in Android manifest using the following method:
<receiver android:name=".activities.widget.UsbBroadCastReceiver"> <intent-filter android:priority="1000"> <action android:name="android.intent.action.MEDIA_MOUNTED"/> <action android:name="android.intent.action.MEDIA_EJECT" /> <data android:scheme="file"/> </intent-filter></receiver>
3. If the broadcast is intercepted by other programs, you will not be able to receive the broadcast. Add one to intent-filter.Android: Priority = "1000"To add the location, refer to the above Code.
4. In my project, the whole program listens to broadcasts,
① The Android manifest code is as follows:
<receiver android:name=".activities.widget.UsbBroadCastReceiver"> <intent-filter android:priority="1000"> <action android:name="android.intent.action.MEDIA_MOUNTED"/> <action android:name="android.intent.action.MEDIA_EJECT" /> <data android:scheme="file"/> </intent-filter></receiver>
Android manifest must be added to intent-Filter
<Data Android: Scheme = "file">,Otherwise, you will not be able to monitor the SD card plugging broadcast. If you register the broadcast with code in the activity, you must add
Ifilter. adddatascheme ("file ")② The broadcast code is as follows:
/** * @createDate * @version v0.5.1 */public class UsbBroadCastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals(Intent.ACTION_MEDIA_EJECT)){ ToastUtil.ToastShort(context, R.string.usb_sdeject); }else if(action.equals(Intent.ACTION_MEDIA_MOUNTED)){ ToastUtil.ToastShort(context, R.string.usb_sdconnect); } }}
Reproduced from girl is coding