Android

Android FileProvider 配置使用

1.註冊FileProvider(AndroidManifest.xml)

<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>

2.創建resource xml file(provider_paths)

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <root-path name="myImage" path="." />
    <files-path name="myImage" path="." />
    <cache-path name="myImage" path="." />
    <external-path name="myImage" path="." />
    <external-files-path name="myImage" path="." />
    <external-cache-path name="myImage" path="." />
</paths>
<root-path/>           => 設備的根目錄new File("/");
<files-path/>          => context.getFilesDir()
<cache-path/>          => context.getCacheDir()
<external-path/>       => Environment.getExternalStorageDirectory()
<external-files-path>  => context.getExternalFilesDirs()
<external-cache-path>  => getExternalCacheDirs()

3.程式碼

val outputFile = File(getFilesDir(), "myImage")
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val imgUri = FileProvider.getUriForFile(applicationContext, BuildConfig.APPLICATION_ID + ".provider", outputFile)
intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri)
startActivityForResult(intent, TAKE_PHOTO_REQUEST_CODE)

發表迴響