最近在整理拍照或从相册中取图片功能,忽然有个想法,就是拍照之后的图片立马能在相册中看到。我们都知道相册里的图片数据是在sd卡挂载的时候扫描的,如果要想拍照之后在相册中看到图片是不能的,但是呢,我们可以向系统发出一条sd挂载的广播,欺骗一下系统图库应用让其去扫描sd卡并加载图片。只要在拍照成功之后加如下代码即可:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
但是,在4.4版本之前的手机上是没啥问题的,4.4版本之后的手机上运行会崩溃,报如下错误:
Caused by:java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.MEDIA_MOUNTED from pid=3843, uid=10085
at android.os.Parcel.readException(Parcel.java:1546)
at android.os.Parcel.readException(Parcel.java:1499)
at android.app.ActivityManagerProxy.broadcastIntent(ActivityManagerNative.java:2825)
at android.app.ContextImpl.sendBroadcast(ContextImpl.java:1339)
at android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:377)
at com.cf.takephoto.MainActivity$3.onSuccess(MainActivity.java:122)
at com.cf.takephoto.IBuilder.onActivityResult(IBuilder.java:124)
at com.cf.takephoto.TakePhoto.onActivityResult(TakePhoto.java:42)
at com.cf.takephoto.MainActivity.onActivityResult(MainActivity.java:109)
...
意思是不允许发送(android.intent.action.MEDIA_MOUNTED
)广播。经过一番搜索,在stackoverflow
得到结论:
It seems that google is trying to prevent this from KITKAT.
Looking at core/rest/AndroidManifest.xml you will notice that broadcast android.intent.action.MEDIA_MOUNTED is protected now. Which means it is a broadcast that only the system can send.
意思是谷歌从4.4版本后保护了一些广播,不允许系统之外的应用发送这些广播,可以AndroidManifest.xml
中看到这条权限被保护了,只有系统能发送。同时给出了两种解决方法:
第一种:
4.4以上版本用(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE
)解决,4.4以下用原来的解决办法
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4版本以上
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(outputFile);
scanIntent.setData(contentUri);
sendBroadcast(scanIntent);
} else {4.4版本以下
Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()));
sendBroadcast(intent);
}
第二种:
此方法兼容4.4以下及以上(推荐使用)
MediaScannerConnection.scanFile(this, new String[] {file.getAbsolutePath()},null, null);
thank
本人水平有限,如有错误,欢迎指正!