Android 7.0 FileProvider適配

Android7.0作了一些權限更改,爲了提升私有文件的安全性,面向 Android 7.0 或更高版本的應用私有目錄被限制訪問。此設置可防止私有文件的原數據泄漏,同事Android7.0若是傳遞 file:// URI 會觸發 FileUriExposedException 異常。適配Android7.0 FileProvider的步驟以下:html

AndroidManifest.xml清單文件的修改
<manifest>
    ......
    <application>
        <!-- Android7.0適配 -->
        <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/file_provider_paths" />
        </provider>
    </application>
</manifest>

${applicationId}.FileProviderapplicationId 爲gradle項目寫法,可修改成本身的包名。java

file_provider_paths.xml文件
<paths>
    <!-- 國內因爲rom比較多,會產生各類路徑,好比華爲的/system/media/,以及外置sdcard -->
    <root-path  name="root" path="." />
    <!-- 表明的根目錄Context.getFilesDir() -->
    <files-path  name="files" path="." />
    <!-- 表明的根目錄getCacheDir() -->
    <cache-path  name="cache" path="." />
    <!-- 表明的根目錄Environment.getExternalStorageDirectory() -->
    <external-path  name="external" path="." />
    <external-files-path  name="external_files" path="." />
    <external-cache-path  name="external_cache" path="." />
    <external-path  name="external_storage_root" path="." />
    <external-path  name="external_storage_files" path="." />
    <external-path  name="external_storage_cache" path="." />
</paths>
代碼中調用
/** * 安裝APK * * @param context * @return */
    public static void installApk(Context context, String apkPath) {
        if (context == null || TextUtils.isEmpty(apkPath)) return;
        File file = new File(apkPath);
        if (!file.exists() || !file.isFile() || file.length() <= 0) return;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //判讀版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //provider authorities
            Uri apkUri = FileProvider.getUriForFile(context, getPackageInfo(context).packageName + ".FileProvider", file);
            //Granting Temporary Permissions to a URI
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

本文分享 CSDN - 秦川小將。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。android

相關文章
相關標籤/搜索