Android 7.0,8.0上安装Apk

本文介绍了一种针对Android 7.0及以上版本的安全优化方案,通过使用FileProvider和自定义的provider名称来实现第三方应用的安装。该方法适用于库项目,并在Android 8.0上自动触发权限请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在网上查找到资料,这里做个总结。

原因:日愈严重的病毒,7.0对安全做了优化。具体原因网上有很多资料,就不说了。

正题:

class方法:

public static boolean installAPK(Context context, File apkFile) {
    if (apkFile.exists()) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, context.getApplicationInfo().processName+".install.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);
        }
        if (context.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            context.startActivity(intent);
        }
        return true;
    } else {
        return false;
    }
}

其中install.fileProvider为mainfests自定义的FileProvider的名称。

配置mainfests

<provider
    android:name=".provider.InstallFileProvider"
    android:authorities="${applicationId}.install.fileProvider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

name:这此是因为有多个provider,所以自定义的provider用于区分。如果你只有一个provider,可以这样写:android.support.v4.content.FileProvider

file_paths.xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="files_root"
        path="Android/data/org.chris.quick/" />
    <external-path
        name="external_storage_root"
        path="." />

</paths>
温馨提示:此种写法可以放在library中,8.0会自动弹出授权界面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值