您的位置:首页 > 移动开发 > Android开发

Android7.0须知--应用间共享文件(FileProvider)

2017-08-19 11:38 736 查看
Android N已经出了好几个预览版了,正式版即将到来,为了迎接Android N的到来,我们接到任务,需要测试并解决我们的应用在7.0上面的适配问题和其他bug 。

测试的时候,发现了一些bug,其中一个bug,就是在打开相册编辑页时,程序会异常退出。

经过排查,发现应用崩溃前,报出FileUriExposedException异常,官网上搜索,发现在Android N的behavior-changes里面,有一些关于 FileUriExposedException 异常的描述:

对于面向 Android N 的应用,Android 框架执行的
StrictMode,API 禁止向您的应用外公开 file://URI。

如果一项包含文件 URI 的 Intent 离开您的应用,应用失败,并出现 FileUriExposedException异常。

若要在应用间共享文件,您应发送一项 content://URI,并授予 URI 临时访问权限。

进行此授权的最简单方式是使用
FileProvider类。 如需有关权限和共享文件的更多信息,

请参阅共享文件

也就是说,对于应用间共享文件这块,Android N中做了强制性要求

以打开图片裁剪为例:

打开相册编辑页面(伪代码)

Intent intent = new Intent("com.android.camera.action.CROP");

String path = "/storage/emulated/0/Pictures/Screenshots/img_test.png";
Uri uri = Uri.parse("file://"+ path);
intent.setDataAndType(uri, "image/*");

intent.putExtra("crop", "true");
intent.putExtra("outputX", 80);
intent.putExtra("outputY", 80);
intent.putExtra("return-data", false);
context.startActivityForResult(intent, 1);




图片编辑页面.jpg

在Android N以下版本,上述代码可以正常打开图片裁剪页面,但是在Android N中,这样是无法打开相册编辑页面的。系统会报错,提示相册应用出错,并抛出FileUriExposedException,程序异常退出。

//部分错误日志:

Process: com.google.android.apps.photos, PID: 24476
android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20160809-234958.png exposed beyond app through Intent.getData()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
at android.net.Uri.checkFileUriExposed(Uri.java:2346)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8933)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8894)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1517)
at android.app.Activity.startActivityForResult(Activity.java:4223)
at cx.startActivityForResult(PG:48)
at de.startActivityForResult(PG:75)
at udg.startActivityForResult(PG:177)
at android.app.Activity.startActivityForResult(Activity.java:4182)


手机弹框提示:



相机异常.png

问题就出现在Uri uri = Uri.parse("file://"+ path); 按照Android N的要求,若要在应用间共享文件,您应发送一项 content://URI,并授予 URI 临时访问权限。

而进行此授权的最简单方式是使用
FileProvider类。(修改后的伪代码在讲述FileProvider的使用时会写)

FileProvider 的使用

官网中关于FileProvider有详细描述,我将主要步骤和使用中应该注意的一些问题大概的说一下。

1.在manifest中添加provider

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.lovexiaoai.myapp">
<application
...>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="cn.lovexiaoai.myapp.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
...
</application>
</manifest>

//exported:要求必须为false,为true则会报安全异常。
//grantUriPermissions:true,表示授予 URI 临时访问权限。


2.资源文件下创建相应的xml文件(如上:则创建filepaths.xml)。

<paths>
<external-path path="images" name="camera_photos" />
</paths>

<files-path/>代表的根目录:
Context.getFilesDir()

<external-path/>代表的根目录:
Environment.getExternalStorageDirectory()

<cache-path/>代表的根目录:
getCacheDir()

==注意==

<external-path path="images/" name="camera_photos" />

这个联合起来的意思就是:可以访问外部存储目录下,images文件夹下的文件。

就是说,我可以将这个文件夹下(以我的测试机为例:/storage/emulated/0/images)的所有文件传递给图片编辑页面。

但是,因为有很多时候,图片来源不确定,而且每款手机的相册所在的文件名称也可能不一样,如果一一添加的话,很麻烦,而且容易遗漏,这里,我用了一个简单的方法,很方便。代码如下,这样的话,我可以传递外部存储设备根目录下的任意一张图片了(包括其子目录)

<external-path path="" name="camera_photos" />

3 FileProvider

File file = new File("/storage/emulated/0/Pictures/Screenshots/img_test.jpg");

//主要修改就在下面3行

/* getUriForFile(Context context, String authority, File file):此处的authority需要和manifest里面保持一致。
photoURI打印结果:content://cn.lovexiaoai.myapp.fileprovider/camera_photos/Pictures/Screenshots/testImg.png 。
这里的camera_photos:对应filepaths.xml中的name
*/
Uri photoURI = FileProvider.getUriForFile(context, "cn.lovexiaoai.myapp.fileprovider", file);

/* 这句要记得写:这是申请权限,之前因为没有添加这个,打开裁剪页面时,一直提示“无法修改低于50*50像素的图片”,
开始还以为是图片的问题呢,结果发现是因为没有添加FLAG_GRANT_READ_URI_PERMISSION。
如果关联了源码,点开FileProvider的getUriForFile()看看(下面有),注释就写着需要添加权限。
*/
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(photoURI, "image/*");

intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("outputX", 80);
intent.putExtra("outputY", 80);
intent.putExtra("return-data", false);
context.startActivityForResult(intent, 1);


下面FileProvider的getUriForFile()方法的注释:

/**
* Return a content URI for a given {@link File}. Specific temporary
* permissions for the content URI can be set with
* {@link Context#grantUriPermission(String, Uri, int)}, or added
* to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then
* {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and
* {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a
* <code>content</code> {@link Uri} for file paths defined in their <code><paths></code>
* meta-data element. See the Class Overview for more information.
*
* @param context A {@link Context} for the current component.
* @param authority The authority of a {@link FileProvider} defined in a
*            {@code <provider>} element in your app's manifest.
* @param file A {@link File} pointing to the filename for which you want a
* <code>content</code> {@link Uri}.
* @return A content URI for the file.
* @throws IllegalArgumentException When the given {@link File} is outside
* the paths supported by the provider.
*/
public static Uri getUriForFile(Context context, String authority, File file) {
final PathStrategy strategy = getPathStrategy(context, authority);
return strategy.getUriForFile(file);
}

关于FileProvider我也是现学现用,如果有什么不对的地方,还望大家指正~



作者:小爱_小世界

链接:http://www.jianshu.com/p/3f9e3fc38eae

來源:简书

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: