如何解决之Android Studio不能自动更新安装apk文件的问题

不能自动更新安装apk是什么原因
原因就是android6.0以下
解决,android7.0以上才能自动更新安装apk
步骤:
第一步骤,添加依赖包一句:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

第二步骤,在AndroidManifest.xml里的application下面添加provider

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.demo.test">
	...
    <application
        ...>
        <!-- ===========添加=========== -->
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.demo.test.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

主要添加的,就是provider标签部分,对于属性android:authorities一定要注意,当中的后面部分,com.demo.test是程序的appId,就是applicationId,在app的build.gradle文件当中可以看到代码
在这里插入图片描述
上面配置当中是否有看到android:resource="@xml/file_paths"呢,这里再来说一下xml下的file_paths

在项目中的res下新建xml目录,并在xml目录当中新建file_paths.xml文件,该文件当中的内容如下:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_files"
        path="" />
</paths>

其实,我的path为空则表示为Environment.getExternalStorageDirectory()的主目录;好了,到此为止将配置做好了,以下是调用程序的安装功能,代码如下:

    /**
     * 安装apk
     */
    protected void installApk(File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //****新增代码****
        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= 24) {
            Uri apkUri = FileProvider.getUriForFile(MainActivity.this, "com.demo.test.fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //执行的数据类型
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

自动更新安装apk如下图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

彬sir哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值