// 在IntentFilter中选择你要监听的行为 IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);// sd卡被插入,且已经挂载 intentFilter.setPriority(1000);// 设置最高优先级 intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);// sd卡存在,但还没有挂载 intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);// sd卡被移除 intentFilter.addAction(Intent.ACTION_MEDIA_SHARED);// sd卡作为 USB大容量存储被共享,挂载被解除 intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);// sd卡已经从sd卡插槽拔出,但是挂载点还没解除 intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);// 开始扫描 intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);// 扫描完成 intentFilter.addDataScheme("file"); registerReceiver(broadcastRec, intentFilter);// 注册监听函数
private final BroadcastReceiver broadcastRec = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals("android.intent.action.MEDIA_MOUNTED"))// SD // 卡已经成功挂载 { imagepath = android.os.Environment.getExternalStorageDirectory();// 你的SD卡路径 Toast.makeText(MyService.this, "我的卡已经成功挂载", 0).show(); } else if (action.equals("android.intent.action.MEDIA_REMOVED")// 各种未挂载状态 || action.equals("android.intent.action.ACTION_MEDIA_UNMOUNTED") || action.equals("android.intent.action.ACTION_MEDIA_BAD_REMOVAL")) { imagepath = android.os.Environment.getDataDirectory();// 你的本地路径 Toast.makeText(MyService.this, "我的各种未挂载状态", 0).show(); }else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)){//开始扫描 Toast.makeText(MyService.this, "开始扫描...", 0).show(); }else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)){//扫描完成 Toast.makeText(MyService.this, "扫描完成...", 0).show(); }else if (action.equals(Intent.ACTION_MEDIA_SHARED)){//扩展介质的挂载被解除 (unmount)。因为它已经作为 USB 大容量存储被共享 Toast.makeText(MyService.this, " USB 大容量存储被共享...", 0).show(); }else { Toast.makeText(MyService.this, "其他状态...", 0).show(); } Log.i(TAG, "imagepath---" + imagepath); } };
unregisterReceiver(broadcastRec);//取消注册
<!-- 在SDCard中创建与删除文件权限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <!-- 往SDCard写入数据权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />