android 7.0以上 FileProvider的使用方法

下載啦、獲取圖片地址啦之類的,7.0以上的Fileprovider使用方法:

 

第一步、聲明文件:
在清單文件AndroidManifest.xml中添加如下代碼,

<application>

......

<provider
     android:name="android.support.v4.content.FileProvider"
     android:authorities="com.project.purse.fileprovider"
     android:exported="false"
     android:grantUriPermissions="true">
     <meta-data
         android:name="android.support.FILE_PROVIDER_PATHS"
         android:resource="@xml/file_paths"/>
</provider>

......

</application>

其中的file_paths需要在res中的xml文件下,新建xml文件,文件名爲:file_paths

 

第二步,配置file_paths.xml文件內容:

<?xml version="1.0" encoding="utf-8"?>
<paths>

    <external-path path="" name="download"/>

    <external-path path="" name="Pictures"/>

</paths>

上述配置中,說明零食存儲區域爲根目錄,相當於

Environment.getExternalStorageDirectory()

下的download文件夾和Pictures文件夾是共享的,其中的Pictures對應上一篇文章: android WebView調起攝像頭並上傳(兼容7.0以上)、返回重定向問題。

下載app等的使用方法:

File saveFile = new File(Environment.getExternalStorageDirectory(), "xiazai.apk");

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    Uri contentUri = FileProvider.getUriForFile(context, "com.***.***.fileprovider", saveFile);
    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
    intent.setDataAndType(Uri.fromFile(saveFile), "application/vnd.android.package-archive");
}

其中的參數2:如果你的包名爲:com.project.bauduu,那參數2的值爲:com.project.bauduu.fileprovider

 

圖片的使用方法爲:

String filePath = Environment.getExternalStorageDirectory() + File.separator
                        + Environment.DIRECTORY_PICTURES + File.separator;
String fileName = "IMG_" + DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";

File fileUri = new File(filePath + fileName);
imageUri = Uri.fromFile(fileUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    imageUri = FileProvider.getUriForFile(getActivity(), "com.***.***" + ".fileprovider", fileUri);//通過FileProvider創建一個content類型的Uri
}

 

發佈了19 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章