Android 7.0+調用其他App打開文件

? 近期需要用到讀取Android設備外存中的JSON和Word,在前期開發時用于調試的是Android 6.0的米4,當拿到實際應用環境(Android 7.0)時,Android 6.0之后的版本增加了運行時權限,應用程序在執行每個需要系統權限的功能時,需要添加權限請求代碼(默認權限禁止),否則應用程序無法響應;查閱官方文檔后發現可以使用FileProvider解決該問題

FileProvider概述

官方描述:FileProvider是ContentProvider的一個特殊的子類,通過創建content:// Uri來替代file:///Uri分享文件給另一個App,來促進安全共享。

原文: FileProvider is a special subclass of ContentProvider that facilitates secure sharing of files associated with an app by creating a content:// Uri for a file instead of a file:/// Uri.

主要步驟:

  1. 定義一個FileProvider
  2. 指定可用文件
  3. 檢索文件的內容URI
  4. 授予URI的臨時權限
  5. 將內容URI提供給其他應用程序

官方文檔鏈接:(https://developer.android.com/reference/android/support/v4/content/FileProvider.html#ServeUri)

定義一個FileProvider

  1. 首先需要在AndroidManifest.xml里申請關于文件的權限
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

或者

   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  1. 同樣,在AndroidManifest.xml中添加以下代碼,允許授權臨時訪問文件

    <manifest>
        ...
        <application>
            ...
            <provider
                android:name="android.support.v4.content.FileProvider"
                android:authorities="com.mydomain.fileprovider"
                android:exported="false"
                android:grantUriPermissions="true">
                ...
            </provider>
            ...
        </application>
    </manifest>  
    

指定可用文件

  1. res 下新建一個xml文件夾,并新建一個 filepath.xml 文件,使用 paths 指定具體文件路徑,

pathsname 屬性是用于之后的調用,path 屬性對應我們需要的文件目錄在對應父節點的路徑

示例如下

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-cache-path  name="external_storage" path="docs/"/>
</paths>
  1. 創建后需要在fileprovider中加入該xml文件
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.example.yyyyz.systonpad.fileprovider"
    android:grantUriPermissions="true"
    android:exported="false">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/filepaths" />
</provider>

? 在 provider 中加入一個 meta-data 元素 , android:name 屬性設為以上默認值即可, android:resource 設為剛才所添加的xml文件文件名。

為文件生成Content Uri

在完成以上兩步后即可在程序中引用你所需要的文件,示例如下

  File docPath = new File(mContext.getExternalCacheDir(), "docs");
  File file = new File(docPath, cadre.getXm() + ".doc");
  if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
      Uri uri = getUriForFile(mContext,
                              BuildConfig.APPLICATION_ID+ ".fileprovider",
                              file);
      intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
      // 設置文件類型為Word
      intent.setDataAndType(uri, "application/msword");
  } else{
      Uri uri = Uri.fromFile(file);
      intent.setDataAndType(uri, "application/msword");
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  }

? 這里 mContext.getExternalCacheDir() 中獲取的路徑 Android\data\包名\cache 我需要的文件路徑為Android\data\包名\cache\docs\ 所以在 child 中設為 “docs“ 。

? 之后對Android系統版本進行判斷,若>=7.0,則創建 content://Uri , 否則創建 file:///Uri

? getUriForFile() 的三個參數 第一個context 無需多說、第二個參數為 包名 + .fileprovider , 第三個參數為之前創建的要打開的file。

為Uri生成暫時的Permissions

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

將Uri提供給其他程序

intent.setDataAndType(uri, "application/msword");
 mContext.startActivity(intent);

官方文檔中介紹了以下6種不同的路徑以及對應的函數

<files-path name="name" path="path" />

? 等價于使用 Context.getFilesDir()

<cache-path name="name" path="path" />

? 等價于使用 getCacheDir()

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

? 等價于使用 Environment.getExternalStorageDirectory().

<external-files-path name="name" path="path" />
等價于使用   `Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)`.
<external-cache-path name="name" path="path" />

? 等價于使用 Context.getExternalCacheDir().

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

? 等價于使用 Context.getExternalMediaDirs(). 需要在api21+中使用

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,084評論 25 708
  • ¥開啟¥ 【iAPP實現進入界面執行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 6,510評論 0 17
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,869評論 18 139
  • 在書中的最后寫道“他上了二級平臺,沿著鐵路線急速地向東走去。他遠遠地看見,頭上包著紅紗巾的惠英,胸前飄著紅領巾的明...
    松果閱讀 672評論 0 3
  • 蘇州,古稱吳,簡稱為蘇,又稱姑蘇、平江等。自古就被文人稱作人間天堂,也有云:上有天堂,下有蘇杭 的美譽...
    一馬當先乎閱讀 752評論 11 9