最近做项目遇到的难题,调用系统拍照获取不到缩略图,非得关机重启才会生成,所以我们要主动通知系统扫描SD卡生成缩略图,
在Android4.4之前也就是以发送一个Action为“Intent.ACTION_MEDIA_MOUNTED”的广播通知执行扫描。如下:
this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
但在Android4.4中,则会抛出以下异常:
W/ActivityManager( 498): Permission Denial: not allowed to send broadcast android.intent.action.MEDIA_MOUNTED from pid=2269, uid=20016
那是因为Android4.4中限制了系统应用才有权限使用广播通知系统扫描SD卡。 解决方式: 使用MediaScannerConnection执行具体文件或文件夹进行扫描。1 Intent mediaScanIntent = new Intent(2 Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);3 String path = "file://"4 + out.getPath();5 Uri contentUri = Uri.parse(path); //out is your output file6 mediaScanIntent.setData(contentUri);7 this.sendBroadcast(mediaScanIntent);
MediaScannerReceiver 源码中的广播接收的部分代码:
1 @Override 2 public void onReceive(Context context, Intent intent) { 3 String action = intent.getAction(); 4 Uri uri = intent.getData(); 5 String externalStoragePath = Environment.getExternalStorageDirectory().getPath(); 6 7 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) { 8 // scan internal storage 9 scan(context, MediaProvider.INTERNAL_VOLUME); 10 } else { 11 if (uri.getScheme().equals("file")) { 12 // handle intents related to external storage 13 String path = uri.getPath(); 14 if (action.equals(Intent.ACTION_MEDIA_MOUNTED) && 15 externalStoragePath.equals(path)) { 16 scan(context, MediaProvider.EXTERNAL_VOLUME); 17 } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) && 18 path != null && path.startsWith(externalStoragePath + "/")) { 19 scanFile(context, path); 20 } 21 } 22 } 23 }
所以最后的代码是:
1 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 2 Intent mediaScanIntent = new Intent( 3 Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 4 String path = "file://" 5 + out.getPath(); 6 Uri contentUri = Uri.parse(path); //out is your output file 7 mediaScanIntent.setData(contentUri); 8 this.sendBroadcast(mediaScanIntent);10 } else {11 sendBroadcast(new Intent(12 Intent.ACTION_MEDIA_MOUNTED,13 Uri.parse("file://"14 + Environment.getExternalStorageDirectory())));15 }