天天看點

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

繼續閱讀