监听SD卡状态变化
public class SDReceiver 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, "准备就绪", Toast.LENGTH_SHORT).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();
}
}
}
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".SDReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MEDIA_MOUNTED"></action>
<action android:name="android.intent.action.MEDIA_REMOVED"></action>
<action android:name="android.intent.action.MEDIA_UNMOUNTED"></action>
<data android:scheme="file" />
</intent-filter>
</receiver>
</application>