监听SD卡状态

第一步,创建一个广播接收者,

 SDReceiver   extends BroadcastReceiver ; 
第二步,在AndroidManifest.xml配置文件中注册广播接收者与配置监SD卡状态发生变化时对应的Action:
  <receiver android:name="com.itheima.sdlistener.SDReceiver">
            <intent-filter >
                <action android:name="android.intent.action.MEDIA_MOUNTED"/>
                <action android:name="android.intent.action.MEDIA_REMOVED"/>
                <action android:name="android.intent.action.MEDIA_UNMOUNTED"/>
                <data android:scheme="file"/>
            </intent-filter>
 </receiver>
第三步,重写广播接受者中OnReceiver方法:
public void onReceive(Context context, Intent intent) {
     
//判断收到的是神马广播
//获取广播中的action
String action = intent.getAction();
 
if(Intent.ACTION_MEDIA_MOUNTED.equals(action)){
Toast.makeText(context, "sd卡就绪", 0).show();
}
else if(Intent.ACTION_MEDIA_REMOVED.equals(action)){
Toast.makeText(context, "sd卡被拔出了", 0).show();
}
else if(Intent.ACTION_MEDIA_UNMOUNTED.equals(action)){
Toast.makeText(context, "sd卡被卸载了", 0).show();
}
 }
posted @ 2017-02-13 13:23  SoulCode  阅读(766)  评论(0编辑  收藏  举报