当我们保存图片后就会发个通知告诉系统让sdcard重新挂载,这样其他程序就会立即找到这张图片。
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MEDIA_MOUNTED);
intent.setData(Uri.fromFile(Environment
.getExternalStorageDirectory()));
sendBroadcast(intent);
但是到了Android4.4就不灵了,Google将MEDIA_MOUNTED的权限提高了,于是就报了一个下面的错误。
W/System.err﹕java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.MEDIA_MOUNTED from pid=18338, uid=10087
在stackoverfollow中找到了一个办法,在高版本中使用ACTION_MEDIA_SCANNER_SCAN_FILE去通知系统重新扫描文件。代码如下:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(mPhotoFile); //out is your output file
mediaScanIntent.setData(contentUri);
CameraActivity.this.sendBroadcast(mediaScanIntent);
} else {
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
}
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}

本文详细介绍了在Android 4.4及以上版本中,由于系统权限提升导致无法正常接收图片保存通知的问题,并提供了解决方案。通过使用ACTION_MEDIA_SCANNER_SCAN_FILE广播来替代旧有的ACTION_MEDIA_MOUNTED方法,实现了在高版本系统中快速扫描并定位新保存的图片。此解决方案有效解决了由于系统权限调整带来的应用间文件交互难题。

被折叠的 条评论
为什么被折叠?



