监听SD卡的插拔这样的需求你肯定会遇到,今天就总结一下关于系统广播的监听。
比如SD卡的插拔监听流程:
比如SD卡的插拔监听流程:
1. 如果是单个Activity监听广播,则在Activity的onCreate方法里面,用下面的代码注册广播
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addDataScheme("file");
registerReceiver(mBroadcastReceiver , iFilter);
2. 如果是整个程序监听广播,则在Android manifest用下面的方法注册广播
<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. 如果广播别别的程序截获,导致你无法收到广播,给intent-filter加上一个android:priority="1000"的属性就行,添加位置,参照上面的代码。
4. 我的项目里面是整个程序监听广播,
①Manifest的代码如下:
<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一定要在intent-filter注意加上<data android:scheme=”file”>,否则无法监听到SD卡插拔广播,如果你在Activity里面用代码注册广播,那一定要加iFilter.addDataScheme("file")
②广播的代码如下:
Android系统源码中有哪些系统广播? 我在之前的博客中有总结,感兴趣的可以看一下:Android源码中常用的系统广播
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);
}
}
}
类似的广播监听方式都是一样的,比如开机广播的监听,插拔耳机的监听,屏幕亮灭的监听,电量低的监听...
Android系统源码中有哪些系统广播? 我在之前的博客中有总结,感兴趣的可以看一下:Android源码中常用的系统广播