package com.atmob.task.utils; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import androidx.core.content.FileProvider; import com.atmob.utils.MMKVUtils; import java.io.File; /** * a simple fault tolerance, aim to handle installation fault cause by apk broken *

* just record installation times of apk file in same path and same file name *

* if that times more than a special number, then delete the file and notify to download */ public class InstallFaultToleranceUtils { private static final String MMKV_PREFIX = "IFTU_"; private static final int MAX_ALLOW_INSTALL_TIMES = 2; public static void installApk(Context context, File apkFile, OnFileDeleteCallback onFileDeleteCallback) { String apkFilePath = apkFile.getPath(); int installTimes = MMKVUtils.getInt(MMKV_PREFIX + apkFilePath, 0); if (installTimes >= MAX_ALLOW_INSTALL_TIMES) { apkFile.delete(); if (onFileDeleteCallback != null) { onFileDeleteCallback.call(); } MMKVUtils.remove(MMKV_PREFIX + apkFilePath); } else { if (onFileDeleteCallback != null) { AppTaskEvent.report(AppTaskEvent.ATE_INSTALL); } toInstall(context, apkFile); MMKVUtils.putInt(MMKV_PREFIX + apkFilePath, ++installTimes); } } private static void toInstall(Context context, File apkFile) { Intent intent = new Intent(Intent.ACTION_VIEW); try { String[] command = {"chmod", "777", apkFile.getAbsolutePath()}; ProcessBuilder builder = new ProcessBuilder(command); builder.start(); } catch (Exception e) { e.printStackTrace(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile); intent.setDataAndType(contentUri, "application/vnd.android.package-archive"); } else { intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } context.startActivity(intent); } public interface OnFileDeleteCallback { void call(); } }