Android N 最新文件Uri传递

解决 Android N 上 安装Apk时报错:android.os.FileUriExposedException: file:///storage/emulated/0/Download/appName-2.3.0.apk exposed beyond app through Intent.getData()

解决方法

1、在AndroidManifest.xml中添加如下代码
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="app的包名.fileProvider"
    android:grantUriPermissions="true"
    android:exported="false">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

注意: 
authorities:app的包名.fileProvider 
grantUriPermissions:必须是true,表示授予 URI 临时访问权限 
exported:必须是false 
resource:中的@xml/file_paths是我们接下来要添加的文件

2、在res目录下新建一个xml文件夹,并且新建一个file_paths的xml文件(如下图)
3、打开file_paths.xml文件添加如下内容
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path path="Android/data/app的包名/" name="files_root" />
    <external-path path="." name="external_storage_root" />
</paths>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

path:需要临时授权访问的路径(.代表所有路径) 
name:就是你给这个访问路径起个名字

4、修改代码适配Android N
Intent intent = new Intent(Intent.ACTION_VIEW);
//判断是否是AndroidN以及更高的版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
startActivity(intent);
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

1、首先我们对Android N及以上做判断; 
2、然后添加flags,表明我们要被授予什么样的临时权限 
3、以前我们直接 Uri.fromFile(apkFile)构建出一个Uri,现在我们使用FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile); 
4、BuildConfig.APPLICATION_ID直接是应用的包名



注解实例二:

接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);
    在Android N以下版本,上述代码可以正常打开图片裁剪页面,但是在Android N中,这样是无法打开相册编辑页面的。系统会报错,提示相册应用出错,并抛出FileUriExposedException,程序异常退出。
  • 问题就出现在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);
        }

获取文件 URI 的方法取决于文件的来源和您的应用程序的运行环境。以下是几种获取文件 URI 的常见方法: 1. 从本地存储器获取文件 URI: ```java File file = new File(Environment.getExternalStorageDirectory(), "example.txt"); Uri uri = Uri.fromFile(file); ``` 2. 从应用程序资源获取文件 URI: ```java Uri uri = Uri.parse("android.resource://com.example.myapp/raw/example"); ``` 3. 从 ContentProvider 获取文件 URI: ```java Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues()); ``` 上述方法仅适用于 Android 7.0 及以下版本。从 Android 7.0 开始,您需要使用 FileProvider 来安全地共享文件 URI。使用 FileProvider 可以确保您的应用程序只能访问您明确授权的文件。 以下是使用 FileProvider 获取文件 URI 的示例代码: ```xml <provider android:name="androidx.core.content.FileProvider" android:authorities="com.example.myapp.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider> ``` ```java File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "example.jpg"); Uri uri = FileProvider.getUriForFile(this, "com.example.myapp.fileprovider", file); ``` 请注意,您需要在 AndroidManifest.xml 文件中注册 FileProvider,并在 res/xml 文件夹中创建 file_paths.xml 文件来指定要共享的文件路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值