美文网首页
Android里安装apk遇到的问题

Android里安装apk遇到的问题

作者: _compass | 来源:发表于2020-07-09 19:23 被阅读0次

代码里安装apk:
res里的xml下加入file_path文件:

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

Menifest里加入:

  <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.xxx.xxx.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">

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

代码里安装:

    private void installApk(Context context, File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //判断版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);//在AndroidManifest中的android:authorities值
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            context.startActivity(install);
        } else {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(install);
        }
    }

其中,file是已经下载的文件。
在8.0版本以上的版本,需要加入权限:

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

以上。

相关文章

网友评论

      本文标题:Android里安装apk遇到的问题

      本文链接:https://www.haomeiwen.com/subject/pbkscktx.html