--- tags: Android --- # Android 11 in Fileprovider ## Fileprovifer 簡介 在Android 7.0以前,可以使用file://uri 的方式去存取其他app的私有目錄,但這樣就會產生因該安全性的風險。所以在Android7.0以後,新增了對檔案跨APP存取的限制,這個限制就是只要嘗試存取其他APP的私有目錄,就會產生android.os.FileUriExposedException的異常。 ### Fileprovider註冊的兩大步驟 1. 在manifest.xml進行註冊 ``` =xml <application> <activity ... /> ... <provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true"> <!-- ressource file to create --> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data> </provider> </application> ``` 2. 在 res/xml目錄下新增共享目錄標識檔案(檔案名稱對應上面的android:recource設定的名稱) ``` =xml <?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-files-path name="image" path="."/> </paths> ``` 其中 paths的標籤可以配置多組,每一組也有多種選擇,具體規則如下: root-path= device_root,也就是File file = new File("/")。 files-path = content.getFileDir() cache-path = content.getCacheDir() external-path = Environment.getExternalStorageDirectory() external-files-path = ContextCompat.getExternalFilesDirs() external-cache-path = ContextCompat.getExternalCacheDirs() 可以看出,這些子元素基本涵蓋內外儲存空間所有目錄路徑,包含應用私有目錄。同時,每個子元素都擁有 name 和 path 兩個屬性。 其中,path 屬性用於指定當前子元素所代表目錄下需要共享的子目錄名稱。 注意:path 屬性值不能使用具體的獨立檔名,只能是目錄名。 而 name 屬性用於給 path 屬性所指定的子目錄名稱取一個別名。後續生成 content:// URI 時,會使用這個別名代替真實目錄名。這樣做的目的,很顯然是為了提高安全性。 以上就是Fileprovider基本的使用方法,而在Android 11以後已經限制了存取特定的外部儲存位置,請參考以下網址: https://developer.android.com/about/versions/11/privacy/storage  文中已經說明如果真的要存取APP外部的儲存位置,就要使用getExternalFilesDirs來存取系統為APP準備的私有儲存空間。因此在path標籤的選用,就使用external-files-path。 ## 參考資料 https://www.itread01.com/content/1548202538.html https://blog.csdn.net/qq_36707431/article/details/107248083 https://segmentfault.com/a/1190000021357383
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up