Bugly升级SDK适配Android N

前言

前几天有个用户在我们论坛反馈一个问题,说他们的app在Android N机型中升级失败了,看了一下反馈的问题,基本确定了是因为Android N收敛了访问共享文件权限,即在Android N中使用intent不允许跨package共享file://URI,如果在工程中设置targetSDK版本为Android N并且有通过Intent传递文件它会抛出FileUriExposedException异常。发现这个问题之后呢,我自然尝试复现一下,由于没有Android 7.0的真机,我就在优测线上租用了一个7.0设备,发现我们SDK在Android 7.0在下载文件完成安装的时候就出现问题了。大家如果以后遇到类似的问题,可以利用优测的云真机来解决没有真机的痛点,节省了成本也提高了效率。

问题所在

前面已经把问题进行了一下描述,我们可以看下出错的代码:

    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(i);

这段代码的意思是,通过intent设置数据和类型,然后通过context在新的task中启动安装apk的程序。
我们看到intent设置数据时,传递的是一个Uri,这个在API<24是没有问题的,但在Android N已经禁止你对外公开file://URI.所以我们SDK的问题就出自Uri.fromFile(file)获取uri的时候。

如何解决?

Android N已经给出明确解决方案,如果你的程序需要在应用间共享文件,您应发送一项 content://URI,并授予 URI 临时访问权限。进行此授权的最简单方式是使用 FileProvider类。

  1. 首先在AndroidManifest中注册FileProvider
    代码示例:
 <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.bugly.upgrade.demo.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

这里要注意一下,FileProvider是support-v4包里面的,所以在你的程序必须要引入support-v4包。
我们可以看到在provider中需要配置相应的meta-data,这个是共享文件的路径,在res目录下新建xml文件夹并新建对应的xml文件(如下面的provider_paths),如下所示:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- /storage/emulated/0/Download/com.bugly.upgrade.demo/.beta/apk-->
    <external-path name="beta_external_apk" path="Download/com.bugly.upgrade.demo/.beta/apk/"/>
    <!--/storage/emulated/0/Android/data/com.bugly.upgrade.demo/files/apk/-->
    <external-path name="beta_external_apk2" path="Android/data/com.bugly.upgrade.demo/files/apk/"/>
</paths>

这里写图片描述

name表示一个URI路径段,path表示指定要分享路径的子目录。可以看到我配置了两个external-path,这两个路径都是beta下载的文件可能存在的路径,举个例子,第一个路径存在的uri如下:
content://com.bugly.upgrade.demo.fileProvider/beta_external_apk/combuglyupgradedemo_21_d778bda9-f3c5-4608-b5ea-2df2a2372f91.apk
可以看到我们配置的beta_external_apk成为了URI的一个路径段。

我们还可以指定以下路径:

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

表示路径在应用中的内部存储区域中files目录下的子目录下,files-path表示Context.getFilesDir()的根目录。
例如:/data/data/com.bugly.upgrade.demo/files

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

表示路径在应用中红内部存储区域中cache目录下的子目录下,cache-path表示Context.getCacheDir()的根目录。
例如:/data/data/com.bugly.upgrade.demo/cache

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

表示路径在外部存储区域根目录的子目录,external-path表示Environment.getExternalStorageDirectory()的根目录。
例如:/storage/emulated/0

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

表示路径在外部存储区域根目录的缓存目录,external-cache-path表示Context.getExternalCacheDir()
例如:/storage/emulated/0/Android/data/com.bugly.upgrade.demo/cache

  1. 通过FileProvider获取Uri路径
    示例代码:
Uri uri = Uri.fromFile(file);

可以更改为:

Uri uri = FileProvider.getUriForFile(context,
        BuildConfig.APPLICATION_ID + ".fileProvider", file);

因为我们SDK不会引入support-v4包,所以不能通过上面这种方式直接获取uri,最后考虑通过反射来调用getUriForFile方法,具体实现如下:

 Intent i = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= 24) {
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            // 反射获取FileProvider类型
            Class<?> clazz = Class.forName("android.support.v4.content.FileProvider");
            if (clazz == null) {
                ELog.error("can't find class android.support.v4.content.FileProvider");
                return false;
            }

            // 通过反射调用FileProvider.getUriForFile
            Uri contentUri = (Uri) Utils.invokeReflectMethod("android.support.v4.content.FileProvider", "getUriForFile"
                    , null, new Class[]{Context.class, String.class, File.class},
                    new Object[]{context, ComInfoManager.getCommonInfo(context).boundID + ".fileProvider", file});

            if (contentUri == null) {
                ELog.error("file location is " + file.toString());
                ELog.error("install failed, contentUri is null!");
                return false;
            }
            i.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            i.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }

        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);

调用反射方法定义如下:

    public static Object invokeReflectMethod(String className, String methodName, Object instance,
            Class<?>[] paramTypes, Object[] params) {
        try {
            Class<?> clazz = Class.forName(className);
            Method method = clazz.getDeclaredMethod(methodName, paramTypes);
            method.setAccessible(true);
            return method.invoke(instance, params);
        } catch (Exception e) {
            return null;
        }
    }

大致的解决方案就如上所示啦,已经在Android 7.0验证通过了,由于在Android 7.0以上强制要求配置FileProvider,但考虑API低于24以下还是沿用之前的方法,所以只在API高于24才会去使用FileProvider。

总结

关于Android N共享文件权限的适配已经完成,还有其他特性还需要我们去验证看是否存在一些bug,其实Android每一个版本的发布都会面临这样一个问题,所以我们去了解每个版本特性的变化还是很有必要的,每次更新targetSdkVersion的时候,最好的实践就是根据特性变化列一个checklist来进行适配。好了,本篇文章内容就这么多,可能有讲得不清楚的地方,请见谅。

参考资料

https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en
http://www.jianshu.com/p/3f9e3fc38eae


欢迎关注我的公众号:wwjblog

这里写图片描述

发布了671 篇原创文章 · 获赞 2751 · 访问量 573万+

猜你喜欢

转载自blog.csdn.net/wwj_748/article/details/52664647
N!
n
N*
今日推荐