在把File轉換為Uri時,會跳出exposed beyond app through ClipData.Item.getUri()是代表這個方法不能用了。
在Android版本SDK 24之後,已經不能直接將檔案(File)物件直接轉成Uri,所以換了個新方法「FileProvider」。
1.首先在res中新建xml資料夾,然後建立provider_paths.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>
2.編輯manifest在<application>中增加<provider>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/xxxxxx">
<!--加這邊-->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
到這邊前置作業就完成了,接下來就可以實作FileProvider
3.使用FileProvider取得Uri路徑(取得圖檔為例):
val imgUri = FileProvider.getUriForFile( this@MainActivity,//context "包名.provider", //(use your app signature + ".provider" ) File(image)//路徑 )
-END-
發佈留言