Android7.0以上手机更新APP并自动进行安装

安卓:7.0及以上是通过FileProvider读取文件和完成更新;

这里就不详细讲解FileProvider的使用了,想了解可以自己再搬搬砖;
下面直接上步骤:
1、在AndroidManifest中添加如下代码

<!-- android 7.0以上安装apk所需要的权限 -->
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.doudui.rongegou.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true"
            >

            <!--元数据  -->
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"
                />
        </provider>

2、在res包下新建file_paths.xml文件
这里我在res下新建一个文件夹xml,再在它下面新建file_paths.xml如下图;
在这里插入图片描述
file_paths.xml内容为:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
//主要内容为paths里的内容
    <paths>
        <external-path
            name="download"
            path="" />
    </paths>
</resources>

3、在apk下载完成并成功里面添加以下代码

public static File file;
//加在成功方法里面
if (Build.VERSION.SDK_INT >= 24) {// 判读版本是否在7.0以上
                    file = new File(getSDPath(MainActivity.this), "demo.apk");
                    Uri apkUri = FileProvider.getUriForFile(MainActivity.this, "com.doudui.rongegou.fileprovider", file);// 在AndroidManifest中的android:authorities值
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(Uri.fromFile(new File(Environment
                                    .getExternalStorageDirectory(), "demo.apk")),
                            "application/vnd.android.package-archive");
                    startActivity(intent);
                }
            }

/**
     * 获取路径
     *
     * @param context
     * @return 路径
     */
    public static String getSDPath(Context context) {
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);// 判断sd卡是否存在
        if (sdCardExist) {
            return Environment.getExternalStorageDirectory().toString();// 获取根目录
        } else {
            return context.getCacheDir().getAbsolutePath(); // 获取内置内存卡目录
        }
    }

补充:

//权限管理
implementation ‘com.github.dfqin:grantor:2.1.0’

这里可以使用上面的依赖,一行代码搞定Android6.0动态权限授权、权限管理

引用:
GitHub上的详细讲解

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值