為安卓項目添加FileProvider


簡單記錄

android7.0開始出現FileProvider。從一個小白角度看需要注意這幾點:

  • Manifest.xml中添加provider節點
  • 添加xml文件
  • 模塊的build.gradle中添加com.android.support包的支持
  • 確保provider節點中的authorities的值和content uri的基礎域名一致

具體細節

以SNPE1.25的android程序為例。

最新的Android Studio似乎不能用 android sdk 26,也就意味着必須用FileProvider了。需要在Manifest.xml中的application節點內,添加一段:

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="snpe"
            android:enabled="true"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>

其中,@xml/provider_paths是需要添加的xml文件,需要在src/main/res下的xml目錄(如果沒有則新建)新建provider_paths.xml文件,內容:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external_files"
        path="./" />
</paths>

app模塊的build.gradle中,最后一段,確保包含如下:


dependencies {
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:recyclerview-v7:27.1.1'
    implementation 'com.android.support:exifinterface:27.1.1'
    implementation 'com.android.support:support-v4:27.1.1'

    implementation(name: 'snpe-release', ext:'aar')
    testImplementation 'junit:junit:4.12'
}

從snpe的java代碼,確保provider節點中的authorities的值和content uri的基礎域名一致。生成的uri將以content://com.example.myapp.fileprovider作為開頭。

這里我從Model.java看到:public static final Uri MODELS_URI = Uri.parse("content://snpe/models");,因此Manifest.xml中設定 android:authorities="snpe"

參考

Android爬坑之旅之FileProvider(Failed to find configured root that contains)


免責聲明!

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



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