InstallFaultToleranceUtils.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package com.atmob.task.utils;
  2. import android.content.Context;
  3. import android.content.Intent;
  4. import android.net.Uri;
  5. import android.os.Build;
  6. import androidx.core.content.FileProvider;
  7. import com.atmob.utils.MMKVUtils;
  8. import java.io.File;
  9. /**
  10. * a simple fault tolerance, aim to handle installation fault cause by apk broken
  11. * <p>
  12. * just record installation times of apk file in same path and same file name
  13. * <p>
  14. * if that times more than a special number, then delete the file and notify to download
  15. */
  16. public class InstallFaultToleranceUtils {
  17. private static final String MMKV_PREFIX = "IFTU_";
  18. private static final int MAX_ALLOW_INSTALL_TIMES = 2;
  19. public static void installApk(Context context, File apkFile, OnFileDeleteCallback onFileDeleteCallback) {
  20. String apkFilePath = apkFile.getPath();
  21. int installTimes = MMKVUtils.getInt(MMKV_PREFIX + apkFilePath, 0);
  22. if (installTimes >= MAX_ALLOW_INSTALL_TIMES) {
  23. apkFile.delete();
  24. if (onFileDeleteCallback != null) {
  25. onFileDeleteCallback.call();
  26. }
  27. MMKVUtils.remove(MMKV_PREFIX + apkFilePath);
  28. } else {
  29. if (onFileDeleteCallback != null) {
  30. AppTaskEvent.report(AppTaskEvent.ATE_INSTALL);
  31. }
  32. toInstall(context, apkFile);
  33. MMKVUtils.putInt(MMKV_PREFIX + apkFilePath, ++installTimes);
  34. }
  35. }
  36. private static void toInstall(Context context, File apkFile) {
  37. Intent intent = new Intent(Intent.ACTION_VIEW);
  38. try {
  39. String[] command = {"chmod", "777", apkFile.getAbsolutePath()};
  40. ProcessBuilder builder = new ProcessBuilder(command);
  41. builder.start();
  42. } catch (Exception e) {
  43. e.printStackTrace();
  44. }
  45. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  46. intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
  47. Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile);
  48. intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
  49. } else {
  50. intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
  51. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  52. }
  53. context.startActivity(intent);
  54. }
  55. public interface OnFileDeleteCallback {
  56. void call();
  57. }
  58. }