我们或许经常会遇到这种情况,明明保存了图片,但是当你打开图片时,却没有找到这张图片,手机重启之后才能看到。这是因为SD卡并没有重新挂载,图库也无法把这张图片加载进去,解决这个问题非常简单,只需要我们模拟一个广播,使SD卡重新挂载即可!
public static void sendBroadCaseRemountSDcard(Activity activity,String filepath) {
try{
if(filepath==null){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(Environment.getExternalStorageDirectory()); //指定SD卡路径
mediaScanIntent.setData(contentUri);
activity.sendBroadcast(mediaScanIntent);
}
else {
activity.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
}
}
else{
Uri data = Uri.parse("file://"+filepath);
activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));
}
}
catch(Exception ex){
LogUtil.WriteError(ex);
Log.e("sendBroadCaseRemountSDcard",ex.getMessage());
ToastUtil.show(activity, "重新挂载SD卡失败,请重启手机查看图片");
}
}
扯淡,这根本没用,要重新加载,必须要扫描文件,要重新挂载文件夹,也是要递归扫描文件下的所有文件夹。
实现代码如下:
//扫描文件 public static void fileScan(Activity activity,String file){ Uri data = Uri.parse("file://"+file); activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data)); } //扫描文件夹 public static void folderScan(Activity activity,String path){ File file = new File(path); if(file.isDirectory()){ File[] array = file.listFiles(); for(int i=0;i<array.length;i++){ File f = array[i]; if(f.isFile()){//FILE TYPE String name = f.getName(); if(name.contains(".mp3")){ fileScan(activity,f.getAbsolutePath()); } } else {//FOLDER TYPE folderScan(activity,f.getAbsolutePath()); } } } }