FileProvider使用


*** FileProvider只能為你指定的目錄下files生成content URI。通過屬性paths,在xml文件中指定它的內存區域和路徑。例如,下面的paths告訴FileProvider,打算為你的私有文件images/子目錄請求content URIs。至少一個請求子元素。

 

  1. <paths xmlns:android="http://schemas.android.com/apk/res/android">
  2. <files-path name="my_images" path="images/"/>
  3. </paths>

*** name和path

name:uri路徑片段。為了執行安全,這個值隱藏你所共享的子目錄名。此值的子目錄名包含在路徑屬性中。

path:你所共享的子目錄。雖然name屬性是一個URI路徑片段,但是path是一個真實的子目錄名。注意,path是一個子目錄,而不是單個文件或者多個文件。


1.files-path

 

<files-path name="name" path="path" />

代表與Context.getFileDir()相同的文件路徑

2.cache-path

 

<cache-path name="name" path="path" />

代表與getCacheDir()相同的文件路徑

3.external-path

 

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

代表與Environment.getExternalStorageDirectory()相同的文件路徑

4.external-files-path

 

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

代表與Context#getExternalFilesDir(String) 和Context.getExternalFilesDir(null)相同的文件路徑

5.external-cache-path

 

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

代表與Context.getExternalCacheDir()相同的文件路徑

 

使用:

1.新建res/xml/file_paths.xml文件

 

  1. <paths xmlns:android="http://schemas.android.com/apk/res/android">
  2. <files-path name="my_images" path="images/"/>
  3. <files-path name="my_docs" path="docs/"/>
  4. </paths>

2.配置AndroidManifest.xml

*** android:authorities在FileProvider中使用

 

  1. <provider
  2. android:name="android.support.v4.content.FileProvider"
  3. android:authorities="com.mydomain.fileprovider"
  4. android:exported="false"
  5. android:grantUriPermissions="true">
  6. <meta-data
  7. android:name="android.support.FILE_PROVIDER_PATHS"
  8. android:resource="@xml/file_paths" />
  9. </provider>

3.使用FileProvider

*** 返回URI:content://com.mydomain.fileprovider/my_images/default_image.jpg.

 

  1. File imagePath = new File(Context.getFilesDir(), "images");
  2. File newFile = new File(imagePath, "default_image.jpg");
  3. Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);

4.自定義FileProvider

 

  1. class MyFileProvider extends FileProvider {}
  2. AndroidMenifest.xml中配置
android:name
android:authorities即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM