近期在项目中须要对外部存储设备的状态进行监听,所以整理了此笔记,以便日后查看。
外部存储设备的状态变化时发出的广播
对照不同状态下的广播
1. 插入外部SD卡时:
2. 移除外部SD卡时:
3. 连接PC进入USB大容量存储模式时:
4. 连接PC退出USB大容量存储模式时:
代码实现监听
public void startListen()
{
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
intentFilter.setPriority(1000);
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
intentFilter.addAction(Intent.ACTION_MEDIA_SHARED);
intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
intentFilter.addAction(Intent.ACTION_MEDIA_EJECT);
intentFilter.addAction(Intent.ACTION_MEDIA_NOFS);
intentFilter.addAction(Intent.ACTION_MEDIA_BUTTON);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intentFilter.addDataScheme("file");
registerReceiver(broadcastRec, intentFilter);
} private final BroadcastReceiver broadcastRec = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d("MediaAction", action);
if (action.equals("android.intent.action.MEDIA_MOUNTED"))
{
//todo
} else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED))
{
//todo
}else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)){
}else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)){
}else if (action.equals(Intent.ACTION_MEDIA_SHARED)){
}else {
}
}
};