Android7.0应用间共享文件不再支持传递file://此类uri,而是通过FileProvider来实现,具体适配请看这篇文章。我这里的适配代码是:

在我使用到系统自带相片裁剪的时候,调试过程中出现了App闪退。在调用系统相机返回时,我们一般通过一个File的Uri给Intent去启动相机,相机拍摄后我们去找对应的File。下面的代码是拿到File后的操作。

第106行是给Intent设置原图的uri,intent.setDataAndType方法传入的uri必须是content://形式的uri,如果是file://形式的uri,在7.0以上的手机上会报错,原因就是需要适配。
然后第117是给一个裁剪结果输出的uri,裁剪好了后我们去这个位置找图片就行了,但在开发中发现这里必须传入的是file://形式的uri,如果是content://形式的uri会出现错误,出错的图就不放啦,自己试试就看到了。
在打开系统相册返回时,我们一般通过返回Intent.getData()来获取相册选中的图片uri,此uri在我手机上是content://形式的,可以省去上图106行的转换操作通过intent.setDataAndType直接设置,在4.0还是4.4以下不是content://形式的返回uri,需要再适配下。
还有一个黑科技,无需设置FileProvider,只需在application的oncreate里加上下面三行就行了:
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();
网友评论