项目中要做媒体扫描,需要检测sd插拔事件。写了个demo分析下。
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
onReceiveMediaBroadcast(intent);
}
};
//onReceive方法:
private void onReceiveMediaBroadcast(Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
Log.i(Intent.ACTION_MEDIA_MOUNTED);
} else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
Log.i(Intent.ACTION_MEDIA_UNMOUNTED);
} else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
Log.i(Intent.ACTION_MEDIA_SCANNER_STARTED);
} else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
Log.i(Intent.ACTION_MEDIA_SCANNER_FINISHED);
} else if (action.equals(Intent.ACTION_MEDIA_BAD_REMOVAL)) {
Log.i(Intent.ACTION_MEDIA_BAD_REMOVAL);
}
else if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
Log.i(Intent.ACTION_MEDIA_EJECT);
}
else if (action.equals(Intent.ACTION_MEDIA_REMOVED)) {
Log.i(Intent.ACTION_MEDIA_REMOVED);
}
}
//注册广播接收器:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
intentFilter.addAction(Intent.ACTION_MEDIA_EJECT);
intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
intentFilter.addDataScheme("file");
registerReceiver(mReceiver, intentFilter);
log信息:
插卡:系统打出来的状态,{removed}->{unmounted}->{checking}->{mounted}
我的程序打印信息,android.intent.action.MEDIA_UNMOUNTED->android.intent.action.MEDIA_MOUNTED
->android.intent.action.MEDIA_SCANNER_STARTED->android.intent.action.MEDIA_SCANNER_FINIDHED
拔卡:系统打出来的状态,{mounted}->{umounted}->{removed}
我的程序打印信息,android.intent.action.MEDIA_EJECT->android.intent.action.MEDIA_UNMOUNTED
->android.intent.action.MEDIA_REMOVED