欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android安装apk文件并适配Android 7.0详解

程序员文章站 2023-12-03 11:03:16
android安装apk文件并适配android 7.0详解 首先在androidmanifest.xml文件,activity同级节点注册provider:...

android安装apk文件并适配android 7.0详解

首先在androidmanifest.xml文件,activity同级节点注册provider:

<provider
      android:name="android.support.v4.content.fileprovider"
      android:authorities="${applicationid}.file_provider"
      android:exported="false"
      android:granturipermissions="true">
      <meta-data
        android:name="android.support.file_provider_paths"
        android:resource="@xml/file_paths" />
    </provider>

将apk文件下载到此路径:

string cachepath = (
            getexternalfilesdir("upgrade_apk") +
                file.separator +
                getpackagename() +
                ".apk");

在res目录xml文件夹下创建名为file_paths的文件:upgrade_apk代表上面保存路径的文件夹名称,可随意更改,相同即可。

<?xml version="1.0" encoding="utf-8"?>
<paths>
  <external-files-path name="bga_upgrade_apk" path="upgrade_apk" />
</paths>

最后编写代码,区分不同android系统版本号,安装apk(注意:【com.apkinstall.demo】要替换自己应用的包名)

 /**
       * 安装 apk 文件
       *
       * @param apkfile
       */
      public void installapk(file apkfile) {
        intent installapkintent = new intent();
        installapkintent.setaction(intent.action_view);
        installapkintent.addcategory(intent.category_default);
        installapkintent.setflags(intent.flag_activity_new_task);

        if (build.version.sdk_int > build.version_codes.m) {
          installapkintent.setdataandtype(fileprovider.geturiforfile(getapplicationcontext(), "com.apkinstall.demo.file_provider", apkfile), "application/vnd.android.package-archive");
          installapkintent.addflags(intent.flag_grant_read_uri_permission);
        } else {
          installapkintent.setdataandtype(uri.fromfile(apkfile), "application/vnd.android.package-archive");
        }

        if (getpackagemanager().queryintentactivities(installapkintent, 0).size() > 0) {
          startactivity(installapkintent);
        }
      }

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!