Record the basic usage of FileProvider in Android

  1. Create a new file_paths.xml file in the res/xml directory (if there is no xml directory, please create a new one) (the file name is customized, and file_paths is used as an example here).
  2. In the newly created file_paths.xml file, the simple code is as follows:

    <paths>
    <external-path
        name="my_path"  //自定义
        path="" />
    </paths>
    

    There are not only external-paths in paths, but also several other paths, each corresponding to a different storage directory. Not delved into it here. When using it, pay attention to the settings of the corresponding permissions.

  3. Add provider in application block in AndroidManifest.xml manifest file

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="应用包名"   //一般为应用包名
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/files_path" />    //与res/xml目录中新建的xml文件对应
    </provider>
    
  4. used in code

    Uri uri = FileProvider.getUriForFile(context, FILE_PROVIDER_AUTHORITY, file);
    where FILE_PROVIDER_AUTHORITY corresponds to the android:authorities attribute value in the AndroidManifest.xml manifest file.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324734934&siteId=291194637