AndroidQ 适配应用内,打开安装本地文件夹下apk

AndroidQ 适配应用内,安装本地文件夹下apk

Android Q(10) 之前,打开本地文件夹下的文件的代码

public static void startInstall(Context context, File file) {
        Uri uri = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
}
	

Android Q(10) 会崩溃,报错:

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///storage/emulated/0/XXX/xx/xxxx.apk typ=application/vnd.android.package-archive }

以上报错的原因:
1: Activity 没有注册或者根本没有该 Activity
2:想要调整的应用本地不存在
3:URI 的文件格式不对
4:没有访问 URI 对应的文件的权限

修改方案:
在AndroidManifest.xml 添加

<!-- 适配AndroidQ, 打开文件,安装apk-->
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="XXX.xx.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        </provider>

在res/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_storage_root"  path="."/>
    <!-- 所有路径下 -->
</paths>

startInstall 方法中的修改:

public static void startInstall(Context context, File file) {
        if (Build.VERSION.SDK_INT >= 29) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri apkUri = FileProvider.getUriForFile(context, "XXX.xx.fileProvider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            try {
                context.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Uri uri = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            context.startActivity(intent);
        }
 }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值