Android7.0須知--應用間共享文件(FileProvider)

我的博客
我的博客:Android7.0須知--應用間共享文件(FileProvider)

Android N已經出了好幾個預覽版了,正式版即將到來,為了迎接Android N的到來,我們接到任務,需要測試并解決我們的應用在7.0上面的適配問題和其他bug 。

測試的時候,發現了一些bug,其中一個bug,就是在打開相冊編輯頁時,程序會異常退出。

經過排查,發現應用崩潰前,報出FileUriExposedException異常,官網上搜索,發現在Android N的behavior-changes里面,有一些關于 FileUriExposedException 異常的描述:

  • 對于面向 Android N 的應用,Android 框架執行的 StrictMode,API 禁止向您的應用外公開 file://URI。
    如果一項包含文件 URI 的 Intent 離開您的應用,應用失敗,并出現 FileUriExposedException異常。

  • 若要在應用間共享文件,您應發送一項 content://URI,并授予 URI 臨時訪問權限。
    進行此授權的最簡單方式是使用 FileProvider類。 如需有關權限和共享文件的更多信息,
    請參閱共享文件

也就是說,對于應用間共享文件這塊,Android N中做了強制性要求

以打開圖片裁剪為例:

  • 打開相冊編輯頁面(偽代碼)

     Intent intent = new Intent("com.android.camera.action.CROP");
    
    String path = "/storage/emulated/0/Pictures/Screenshots/img_test.png";
    Uri uri = Uri.parse("file://"+ path); 
    intent.setDataAndType(uri, "image/*");
    
    intent.putExtra("crop", "true");
    intent.putExtra("outputX", 80);
    intent.putExtra("outputY", 80);
    intent.putExtra("return-data", false);
    context.startActivityForResult(intent, 1);
    
圖片編輯頁面.jpg
  • 在Android N以下版本,上述代碼可以正常打開圖片裁剪頁面,但是在Android N中,這樣是無法打開相冊編輯頁面的。系統會報錯,提示相冊應用出錯,并拋出FileUriExposedException,程序異常退出。

      //部分錯誤日志:
    
        Process: com.google.android.apps.photos, PID: 24476
                                                     android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20160809-234958.png exposed beyond app through Intent.getData()
                                                         at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
                                                         at android.net.Uri.checkFileUriExposed(Uri.java:2346)
                                                         at android.content.Intent.prepareToLeaveProcess(Intent.java:8933)
                                                         at android.content.Intent.prepareToLeaveProcess(Intent.java:8894)
                                                         at android.app.Instrumentation.execStartActivity(Instrumentation.java:1517)
                                                         at android.app.Activity.startActivityForResult(Activity.java:4223)
                                                         at cx.startActivityForResult(PG:48)
                                                         at de.startActivityForResult(PG:75)
                                                         at udg.startActivityForResult(PG:177)
                                                         at android.app.Activity.startActivityForResult(Activity.java:4182)
    

    手機彈框提示:

相機異常.png
  • 問題就出現在Uri uri = Uri.parse("file://"+ path); 按照Android N的要求,若要在應用間共享文件,您應發送一項 content://URI,并授予 URI 臨時訪問權限。
    而進行此授權的最簡單方式是使用 FileProvider類。(修改后的偽代碼在講述FileProvider的使用時會寫)

FileProvider 的使用

  • 官網中關于FileProvider有詳細描述,我將主要步驟和使用中應該注意的一些問題大概的說一下。

  • 1.在manifest中添加provider

      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="cn.lovexiaoai.myapp">
          <application
              ...>
              <provider
                  android:name="android.support.v4.content.FileProvider"
                  android:authorities="cn.lovexiaoai.myapp.fileprovider"
                  android:grantUriPermissions="true"
                  android:exported="false">
                  <meta-data
                      android:name="android.support.FILE_PROVIDER_PATHS"
                      android:resource="@xml/filepaths" />
              </provider>
              ...
          </application>
      </manifest>
    
    //exported:要求必須為false,為true則會報安全異常。
    //grantUriPermissions:true,表示授予 URI 臨時訪問權限。
    
  • 2.資源文件下創建相應的xml文件(如上:則創建filepaths.xml)。

    <paths>
      <external-path path="images" name="camera_photos" />
    </paths>
    
  • ==注意==

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

這個聯合起來的意思就是:可以訪問外部存儲目錄下,images文件夾下的文件。
就是說,我可以將這個文件夾下(以我的測試機為例:/storage/emulated/0/images)的所有文件傳遞給圖片編輯頁面。
但是,因為有很多時候,圖片來源不確定,而且每款手機的相冊所在的文件名稱也可能不一樣,如果一一添加的話,很麻煩,而且容易遺漏,這里,我用了一個簡單的方法,很方便。代碼如下,這樣的話,我可以傳遞外部存儲設備根目錄下的任意一張圖片了(包括其子目錄)

<external-path path="" name="camera_photos" />
  • 3 FileProvider

      File file = new File("/storage/emulated/0/Pictures/Screenshots/img_test.jpg");
        
      //主要修改就在下面3行
        
        /* getUriForFile(Context context, String authority, File file):此處的authority需要和manifest里面保持一致。
        photoURI打印結果:content://cn.lovexiaoai.myapp.fileprovider/camera_photos/Pictures/Screenshots/testImg.png 。
        這里的camera_photos:對應filepaths.xml中的name
        */
        Uri photoURI = FileProvider.getUriForFile(context, "cn.lovexiaoai.myapp.fileprovider", file);
         
         /* 這句要記得寫:這是申請權限,之前因為沒有添加這個,打開裁剪頁面時,一直提示“無法修改低于50*50像素的圖片”,
          開始還以為是圖片的問題呢,結果發現是因為沒有添加FLAG_GRANT_READ_URI_PERMISSION。
          如果關聯了源碼,點開FileProvider的getUriForFile()看看(下面有),注釋就寫著需要添加權限。
          */
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);  
        intent.setDataAndType(photoURI, "image/*");
        
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("outputX", 80);
        intent.putExtra("outputY", 80);
        intent.putExtra("return-data", false);
        context.startActivityForResult(intent, 1);
    

下面FileProvider的getUriForFile()方法的注釋:

     /** 
         * Return a content URI for a given {@link File}. Specific temporary
         * permissions for the content URI can be set with
         * {@link Context#grantUriPermission(String, Uri, int)}, or added
         * to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then
         * {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are
         * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and
         * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a
         * <code>content</code> {@link Uri} for file paths defined in their <code><paths></code>
         * meta-data element. See the Class Overview for more information.
         *
         * @param context A {@link Context} for the current component.
         * @param authority The authority of a {@link FileProvider} defined in a
         *            {@code <provider>} element in your app's manifest.
         * @param file A {@link File} pointing to the filename for which you want a
         * <code>content</code> {@link Uri}.
         * @return A content URI for the file.
         * @throws IllegalArgumentException When the given {@link File} is outside
         * the paths supported by the provider.
         */
        public static Uri getUriForFile(Context context, String authority, File file) {
            final PathStrategy strategy = getPathStrategy(context, authority);
            return strategy.getUriForFile(file);
        }
  • 關于FileProvider我也是現學現用,如果有什么不對的地方,還望大家指正~
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容