1. 程式人生 > >自動更新之安裝apk

自動更新之安裝apk

apk內部自動更新,下載apk後安裝apk的邏輯,優點就是安裝過程中,不會回退到桌面(有閃退的效果,其實不是閃退,是APP原來的程序被殺死了),安裝完成後能顯示完成和開啟,且適配安卓7.0

//安裝下載後的apk檔案
public static void install(final Context cxt, final File file) {
    if (file != null && file.exists()) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri contentUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            contentUri = FileProvider.getUriForFile(cxt, cxt.getPackageName() + ".provider", file);
        } else {
            contentUri = Uri.fromFile(file);
        }
        intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (cxt.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            cxt.startActivity(intent);
        }
    } else {//檔案為空或者不存在
        try {
            ToastUtils.show(cxt, cxt.getString(R.string.file_not_exist));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}