Android7.0之FileProvider

FileProvider是android 7.0出来的新东西,2017开始应该会出现越来越多的7.0机器,所以做好7.0的适配工作也是很有必要的,别到时候出现一堆异常崩溃。在网上搜索FileProvider发现都大同小异,关键是没有get到G点,而且废话一大堆,于是自己看了一下官方文档,发现just so so。

参考官方文档:https://developer.android.google.cn/reference/android/support/v4/content/FileProvider.html


一、FileProvider使用在什么地方

A content URI allows you to grant read and write access using temporary access permissions. When you create an Intent containing a content URI, in order to send the content URI to a client app, you can also call Intent.setFlags() to add permissions. These permissions are available to the client app for as long as the stack for a receiving Activity is active. For an Intent going to a Service, the permissions are available as long as the Service is running.

使用临时授权的方式允许读写content URI。当你创建一个Intent包含content URI,为了发送content URI给其他app,使用Intent.setFlags()添加权限。其他app的activity栈只要是活动的,就能访问权限,service也一样。


二、使用FileProvider步骤

1、定义一个FileProvider


    ...
    
        ...
        
            ...
        
        ...
    
name可以使用系统定义的 android.support.v4.content.FileProvider,也可重写FileProvider methods。authorities使用命名空间domain +"fileprovider"的方式,domain可以自定义。

2、指定可用的文件

在res/xml/file_paths.xml目录下创建新文件,内容如下:


    
    ...
FileProvider的路径必须是先前指定的。

对应Context.getFilesDir().

对应getCacheDir()

对应Environment.getExternalStorageDirectory()

对应Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)

对应Context.getExternalCacheDir()。

可以定义多个:


    
    
修改第一步中的provider,添加 ,android:resource对应我们新建的文件

    

3、生成一个文件的Content URI

File imagePath = new File(Context.getFilesDir(), "images");
File newFile = new File(imagePath, "default_image.jpg");
Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);
getUriForFile()方法返回 content URI,值为content://com.mydomain.fileprovider/my_images/default_image.jpg,注意参数"com.mydomain.fileprovider"和第一步定义的参数一致。

4、为URI临时授权

Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
i.putExtra("xxx", imageFileUri);

把content URI 放到Intent中的setData().

Intent.setFlags()值为 FLAG_GRANT_READ_URI_PERMISSION 或者 FLAG_GRANT_WRITE_URI_PERMISSION或者全部.

5、服务一个Content URI到另一个App

startActivity或者startActivityForResult


三、注意事项

The subdirectory you're sharing. While the name attribute is a URI path segment, the path value is an actual subdirectory name. Notice that the value refers to a subdirectory, not an individual file or files. You can't share a single file by its file name, nor can you specify a subset of files using wildcards.
不能直接分享单个文件或者多个文件路径,必须是子目录(文件夹?)

你可能感兴趣的:(android学习)