SD状态发生改变的时候会对外发送广播。SD卡的状态一般有挂载、未挂载和无SD卡。
清单文件
一个广播接受者可以接受多条广播。这里在意图过滤器中添加是data属性是因为广播也需要进行匹配的。对方发送的广播中有Data属性,这里就应添加Data属性。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="xidian.dy.com.chujia"> <uses-permission android:name="android.permission.RECEIVE_SMS"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="主界面"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".SDstatusReceiver"> <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> </application> </manifest>
接受者
接收者通过getAction来区分是那个广播
package xidian.dy.com.chujia; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; /** * Created by dy on 2016/7/12. */ public class SDstatusReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //判断收到的广播类型 String action = intent.getAction(); if("android.intent.action.MEDIA_MOUNTED".equals(action)){ Toast.makeText(context,"SD已挂载", Toast.LENGTH_LONG).show(); } else if("android.intent.action.MEDIA_REMOVED".equals(action)){ Toast.makeText(context, "无SD", Toast.LENGTH_SHORT).show(); } else if("android.intent.action.MEDIA_UNMOUNTED".equals(action)){ Toast.makeText(context, "SD未挂载", Toast.LENGTH_SHORT).show(); } } }