java豆子

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

统计

android 监听SDCard安装和卸载的代码片段(测试通过)

复制代码
      
// 监听类
private final BroadcastReceiver sdcardListener = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {

String action
= intent.getAction();
Log.d(
"TAG", "sdcard action:::::" + action);
if(Intent.ACTION_MEDIA_MOUNTED.equals(action)
|| Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action)
|| Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action)
){
// SD卡成功挂载

}
else if(Intent.ACTION_MEDIA_REMOVED.equals(action)
|| Intent.ACTION_MEDIA_UNMOUNTED.equals(action)
|| Intent.ACTION_MEDIA_BAD_REMOVAL.equals(action)
){
// SD卡挂载失败

}

}
};

// 注册监听
private void registerSDCardListener(){
IntentFilter intentFilter
= new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
intentFilter.addDataScheme(
"file");
registerReceiver(sdcardListener, intentFilter);
}
复制代码

使用完成后注销监听:

unregisterReceiver(sdcardListener);

posted on   java豆子  阅读(2352)  评论(0编辑  收藏  举报

点击右上角即可分享
微信分享提示