一、如果是单个Activity需要监听广播,推荐使用动态广播
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_CHECKING);
filter.addAction(Intent.ACTION_MEDIA_EJECT);
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addDataScheme("file"); //必须添加,否则无法监听到SD卡插拔广播
registerReceiver(mBroadcastReceiver, filter);
tips:
1.动态注册广播,那在Activity中一定要加 filter.addDataScheme("file"),否则无法监听到SD卡插拔广播
2.一定要记住注册了广播之后需要取消注册,否则会有问题,建议在onResume( )中注册广播,在onPause( )中取消注册
二、如果是整个程序需要监听广播,推荐使用静态广播,在AndroidManifest.xml中用下面的方法注册广播
<receiver android:name=".SDReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_MOUNTED" />
<action android:name="android.intent.action.MEDIA_CHECKING" />
<action android:name="android.intent.action.MEDIA_EJECT" />
<action android:name="android.intent.action.MEDIA_UNMOUNTED" />
<action android:name="android.intent.action.MEDIA_REMOVED" />
<!--必须添加,否则无法监听到SD卡插拔广播-->
<data android:scheme="file" />
</intent-filter>
</receiver>
tips:
静态注册广播,那在AndroidManifest.xml中的intent-filter里加上 <data android:scheme="file" />,否则无法监听到SD卡插拔广播