android 下载apk后安装apk(适配android 7.0)

    为适配7.0以后系统,首先需要在AndroidManifest.xml文件中application节点下定义provider,如下:

  <provider

         android:name=:"android.support.v4.content.FileProvider"

         android:authorities="com.dlgs.vendor.fileprovider"  //自定义名称

         android:export="false"

         android:grantUriPermissions="true">

          <meta-data

                 android:name="android.support.FILE_PROVIDER_PATHS"

                 android:resouce="@xml/file_paths"/>   // xml文件,

</provider>

在res下创建xml目录,在xml目录下创建file_paths.xml文件,文件里的内容为:

<?xml version="1.0" encoding="utf-8"?>
<!--external-path用来指定Uri共享,name属性是起的名称,path属性的值表示共享的具体路径,设置空值表示整
个SD卡共享-->
<path xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path=""/>
</path>

安装apk的方法:

    /**
     * 安装apk
     * @param apkPath apk的绝对路径
     */
    private void installApk(String apkPath)
    {
        Intent intent = new Intent("android.intent.action.VIEW");
        // 下面这句代码一定不能少,不然安装后不会进入打开/完成 的选择页面
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

       // android 7.0 以后
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
        {
            Uri apkUri = FileProvider.getUriForFile(context,            //所在activity的上下文
                                                    "com.dlgs.vendor.fileprovider", //AndroidManifest.xml文件中provider里的authorities值
                                                    new File(apkPath));
            // 临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri,
                                  "application/vnd.android.package-archive");
        } else
        {

            // android 7.0 以前
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setDataAndType(Uri.parse("file:" + apkPath),
                                  "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

 注意,一定要添加intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);这句代码,不然更新安装apk后会进入手机桌面;

猜你喜欢

转载自blog.csdn.net/tangjx2016/article/details/84890435