android 代码安装apk

先上代码,代码兼容7.0

    /**
     * 安装apk
     */
    private void installApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        String type = "application/vnd.android.package-archive";
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileProvider", newApkFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(newApkFile);
        }
        intent.setDataAndType(uri, type);
        activity.startActivity(intent);
    }

对于需要兼容7.0需要在在AndroidManifest中添加provider

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

上段代码中的file_paths是定义在res下的xml文件夹中的文件

<paths>
    <external-path name="external_storage_root" path="." />
</paths>

其中external-path节点表示Environment.getExternalStorageDirectory()路径
path表示apk文件在Environment.getExternalStorageDirectory()路径下的文件夹名称

最后如果需要兼容8.0手机需要添加权限

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

附上两个方法

获取当前版本号

        try {
            PackageManager manager = activity.getPackageManager();
            PackageInfo info = manager.getPackageInfo(activity.getPackageName(), 0);
            versionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

获取apk文件版本号

    private int getVersionCodeFromApk(String path) {
        PackageManager pm = activity.getPackageManager();
        PackageInfo packInfo = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
        int versionCode;
        try {
            versionCode = packInfo.versionCode;
        } catch (Exception e) {
            versionCode = 0;
        }
        return versionCode;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,427评论 19 139
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 11,730评论 0 17
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,526评论 25 709
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,477评论 2 59
  • 你对待家人的态度,决定你的未来 哈佛大学曾经做过一个试验,为了探寻成功的秘诀,他...
    红尘一轻骑阅读 2,744评论 0 0