問(wèn)題
以下是一段簡(jiǎn)單的代碼灰蛙,它調(diào)用系統(tǒng)的相機(jī)app來(lái)拍攝照片:
void takePhoto(String cameraPhotoPath) {
File cameraPhoto = new File(cameraPhotoPath);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraPhoto));
startActivityForResult(takePhotoIntent, REQUEST_TAKE_PHOTO);
}
在一般情況下,運(yùn)行沒有任何問(wèn)題隔躲;可是當(dāng)把targetSdkVersion指定成24及之上并且在API>=24的設(shè)備上運(yùn)行時(shí)摩梧,會(huì)拋出異常:
android.os.FileUriExposedException: file:///storage/emulated/0/DCIM/IMG_20170125_144112.jpg exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
at android.net.Uri.checkFileUriExposed(Uri.java:2346)
at android.content.ClipData.prepareToLeaveProcess(ClipData.java:832)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8909)
...
原因
我們來(lái)看一下FileUriExposedException
的文檔:
The exception that is thrown when an application exposes a
file://
Uri to another app.
This exposure is discouraged since the receiving app may not have access to the shared path. For example, the receiving app may not have requested the
READ_EXTERNAL_STORAGE
runtime permission, or the platform may be sharing the Uri across user profile boundaries.
Instead, apps should use
content://
Uris so the platform can extend temporary permission for the receiving app to access the resource.
This is only thrown for applications targeting N or higher. Applications targeting earlier SDK versions are allowed to share
file://
Uri, but it's strongly discouraged.
總而言之,就是Android不再允許在app中把file://
Uri暴露給其他app宣旱,包括但不局限于通過(guò)Intent或ClipData 等方法仅父。
原因在于使用file://
Uri會(huì)有一些風(fēng)險(xiǎn),比如:
- 文件是私有的浑吟,接收
file://
Uri的app無(wú)法訪問(wèn)該文件笙纤。 - 在Android6.0之后引入運(yùn)行時(shí)權(quán)限,如果接收
file://
Uri的app沒有申請(qǐng)READ_EXTERNAL_STORAGE權(quán)限组力,在讀取文件時(shí)會(huì)引發(fā)崩潰省容。
因此,google提供了FileProvider
燎字,使用它可以生成content://
Uri來(lái)替代file://
Uri蓉冈。
解決方案
先上解決方案,感興趣的同學(xué)可以看下一節(jié)FileProvider
的具體講解轩触。
首先在AndroidManifest.xml
中添加provider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
res/xml/provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
然后修改代碼
void takePhoto(String cameraPhotoPath) {
File cameraPhoto = new File(cameraPhotoPath);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri photoUri = FileProvider.getUriForFile(
this,
getPackageName() + ".provider",
cameraPhoto);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(takePhotoIntent, REQUEST_TAKE_PHOTO);
}
FileProvider
使用content://
Uri的優(yōu)點(diǎn):
- 它可以控制共享文件的讀寫權(quán)限寞酿,只要調(diào)用
Intent.setFlags()
就可以設(shè)置對(duì)方app對(duì)共享文件的訪問(wèn)權(quán)限,并且該權(quán)限在對(duì)方app退出后自動(dòng)失效脱柱。相比之下伐弹,使用file://
Uri時(shí)只能通過(guò)修改文件系統(tǒng)的權(quán)限來(lái)實(shí)現(xiàn)訪問(wèn)控制,這樣的話訪問(wèn)控制是它對(duì)所有 app都生效的榨为,不能區(qū)分app惨好。 - 它可以隱藏共享文件的真實(shí)路徑。
定義FileProvider
在AndroidManifest.xml
的<application>
節(jié)點(diǎn)中添加<provider>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
android:authorities
是用來(lái)標(biāo)識(shí)provider的唯一標(biāo)識(shí)随闺,在同一部手機(jī)上一個(gè)"authority"串只能被一個(gè)app使用日川,沖突的話會(huì)導(dǎo)致app無(wú)法安裝。我們可以利用manifest placeholders來(lái)保證authority的唯一性矩乐。android:exported
必須設(shè)置成false
龄句,否則運(yùn)行時(shí)會(huì)報(bào)錯(cuò)java.lang.SecurityException: Provider must not be exported
回论。android:grantUriPermissions
用來(lái)控制共享文件的訪問(wèn)權(quán)限,也可以在java代碼中設(shè)置分歇。
指定路徑和轉(zhuǎn)換規(guī)則
FileProvider會(huì)隱藏共享文件的真實(shí)路徑傀蓉,將它轉(zhuǎn)換成content://
Uri路徑,因此职抡,我們還需要設(shè)定轉(zhuǎn)換的規(guī)則葬燎。android:resource="@xml/provider_paths"
這個(gè)屬性指定了規(guī)則所在的文件。
res/xml/provider_paths.xml:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path path="." name="root" />
<files-path path="images/" name="my_images" />
<files-path path="audios/" name="my_audios" />
...
</paths>
<paths>
中可以定義以下子節(jié)點(diǎn)
子節(jié)點(diǎn) | 對(duì)應(yīng)路徑 |
---|---|
files-path | Context.getFilesDir() |
cache-path | Context.getCacheDir() |
external-path | Environment.getExternalStorageDirectory() |
external-files-path | Context.getExternalFilesDir(null) |
external-cache-path | Context.getExternalCacheDir() |
file://
到content://
的轉(zhuǎn)換規(guī)則:
- 替換前綴:把
file://
替換成content://${android:authorities}
缚甩。 - 匹配和替換
- 遍歷<paths>的子節(jié)點(diǎn)谱净,找到最大能匹配上文件路徑前綴的那個(gè)子節(jié)點(diǎn)。
- 用path的值替換掉文件路徑里所匹配的內(nèi)容擅威。
- 文件路徑剩余的部分保持不變岳遥。
需要注意的是,文件的路徑必須包含在xml中裕寨,也就是2.1中必須能找到一個(gè)匹配的子節(jié)點(diǎn),否則會(huì)拋出異常:
java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.xxx/cache/test.txt
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:679)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:378)
...
代碼中生成Content Uri
File imagePath = new File(Context.getFilesDir(), "images");
File newFile = new File(imagePath, "2016/pic.png");
Uri contentUri = getUriForFile(getContext(), getPackageName() + ".fileprovider", newFile);
設(shè)置文件的訪問(wèn)權(quán)限
有兩種設(shè)置權(quán)限的辦法:
- 調(diào)用
Context.grantUriPermission(package, uri, modeFlags)
派继。這樣設(shè)置的權(quán)限只有在手動(dòng)調(diào)用Context.revokeUriPermission(uri, modeFlags)
或系統(tǒng)重啟后才會(huì)失效宾袜。 - 調(diào)用
Intent.setFlags()
來(lái)設(shè)置權(quán)限。權(quán)限失效的時(shí)機(jī):接收Intent
的Activity
所在的stack銷毀時(shí)驾窟。
題外話:ContentProvider的一個(gè)小技巧
許多Android SDK在使用前往往需要使用者調(diào)用初始化代碼:SomeSdk.init(Context)
庆猫,其實(shí)借助ContentProvider
就可以把這一步省略掉。
原理是在SDK的AndroidManifest
里注冊(cè)一個(gè)ContentProvider
绅络,在它的OnCreate
中進(jìn)行SDK的初始化工作月培。ContentProvider
會(huì)在app進(jìn)程被創(chuàng)建時(shí)創(chuàng)建,并且在它的onCreate
里可以拿到Context的引用恩急。
具體實(shí)現(xiàn)可以參照How does Firebase initialize on Android?
參考文檔
- FileProvider
- file:// scheme is now not allowed to be attached with Intent on targetSdkVersion 24 (Android Nougat). And here is the solution.
- How does Firebase initialize on Android?
打個(gè)廣告
美團(tuán)平臺(tái)及酒旅事業(yè)群招人啦杉畜,歡迎加入我們!
我可以幫忙內(nèi)推衷恭,簡(jiǎn)歷請(qǐng)發(fā)到我郵箱gelitenight@gmail.com
【美團(tuán)網(wǎng)】高級(jí)Android開發(fā)工程師
工作內(nèi)容: 負(fù)責(zé)美團(tuán)酒店此叠、旅游產(chǎn)品 Android 客戶端的設(shè)計(jì)、開發(fā)與改進(jìn)随珠。
- 3年以上工作經(jīng)驗(yàn)灭袁,2年以上Android開發(fā)經(jīng)驗(yàn);
- 熟悉Android系統(tǒng)窗看,熟悉Android軟件的開發(fā)茸歧、測(cè)試、分發(fā)流程显沈;
- 良好的編程風(fēng)格软瞎,扎實(shí)的編程基礎(chǔ)和數(shù)據(jù)結(jié)構(gòu)算法基礎(chǔ);
- 熟悉移動(dòng)網(wǎng)絡(luò)的特性,對(duì)網(wǎng)絡(luò)編程和常用網(wǎng)絡(luò)協(xié)議有較深刻理解和經(jīng)驗(yàn)铜涉;
- 有一定的架構(gòu)設(shè)計(jì)能力智玻,良好的編碼能力,編寫文檔能力芙代;
- 熱愛互聯(lián)網(wǎng)和新技術(shù)吊奢,具有極強(qiáng)的快速學(xué)習(xí)能力;
- 有以下特征優(yōu)先考慮:
- 有開源作品或技術(shù)博客(需原創(chuàng)技術(shù)文章)纹烹;
- 熟悉Socket編程页滚。
北京、上海铺呵、廈門裹驰、成都都有職位,更多職位請(qǐng)見職位列表片挂。
本文遵循“署名-非商業(yè)性使用-相同方式共享”的創(chuàng)作共同協(xié)議幻林,歡迎轉(zhuǎn)載,轉(zhuǎn)載時(shí)請(qǐng)注明作者和出處音念。
作者: gelitenight
出處: 使用FileProvider解決file:// URI引起的FileUriExposedException