天天看点

android7.0适配——app版本更新

android8.0适配链接

以下代码可以直接使用

第一步,配置清单文件

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.hibabypsy.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>
           

代码中红色部分为包名,替换成自己的即可。蓝色字体部分用于配置共享文件路径。

第二步,填写共享文件路径

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

因为我的文件是在外部存储卡中,使用<external-path>标签,而文件路径为

String url=Environment.getExternalStorageDirectory().getAbsolutePath()  +  "/Download/mengbao.apk";

所以,红色部分只提取了文件夹路径即可

第三步,安装

/**
     *  安装下载的apk文件
     * @param context  上下文
     * @param sdPath   apk存储路径
     */
    private static void installApk(Context context, final String sdPath) {

        String url=sdPath+"/Download/mengbao.apk";
        final File file= new File(url);
        if(!file.exists()){
            return;
        }

        Log.d("下载进度", "准备安装 。设备SDK = "+Build.VERSION.SDK_INT);
        Intent intent= new Intent(Intent.ACTION_VIEW);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {// sdk >= 24
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri contentUri = FileProvider.getUriForFile(context,
                    context.getApplicationContext().getPackageName() + ".provider",
                    file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            Uri uri = Uri.fromFile(file);//或者 Uri.parse("file://"+file.toString()
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }


        context.startActivity(intent);

        android.os.Process.killProcess(android.os.Process.myPid());


    }
           

    如果不这样设置,会报以下异常:

android7.0适配——app版本更新

参考:

http://blog.csdn.net/ruancoder/article/details/67639621

http://blog.csdn.net/yy1300326388/article/details/52787853

https://www.jianshu.com/p/55b817530fa3

https://zhuanlan.zhihu.com/p/26139355

继续阅读