//类UpdateInfo //类 public class UpdateInstallReceiver extends BroadcastReceiver { private static UpdateInfo mUpdateInfo; @Override public void onReceive(Context context, Intent intent) { //获取到网络上apk的信息 mUpdateInfo = UpdateManager.getmUpdateInfo(); switch (Objects.requireNonNull(intent.getAction())) { case Intent.ACTION_PACKAGE_ADDED: // Toast.makeText(context, "有应用被添加", Toast.LENGTH_LONG).show(); UpdateUtils.clearUpdateApk(context, mUpdateInfo.getApkName()); break; case Intent.ACTION_PACKAGE_REMOVED: // Toast.makeText(context, "有应用被删除", Toast.LENGTH_LONG).show(); UpdateUtils.clearUpdateApk(context, mUpdateInfo.getApkName()); break; case Intent.ACTION_PACKAGE_REPLACED: // Toast.makeText(context, "有应用被替换", Toast.LENGTH_LONG).show(); UpdateUtils.clearUpdateApk(context, mUpdateInfo.getApkName()); break; case Intent.ACTION_PACKAGE_CHANGED: // Toast.makeText(context, "有应用被改变", Toast.LENGTH_LONG).show(); break; case Intent.ACTION_PACKAGE_RESTARTED: // Toast.makeText(context, "有应用被重启", Toast.LENGTH_LONG).show(); break; } } } //注册 UpdateInstallReceiver updateInstallReceiver = new UpdateInstallReceiver(); IntentFilter intentFilter1 = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter1.addAction(Intent.ACTION_PACKAGE_ADDED); intentFilter1.addAction(Intent.ACTION_PACKAGE_REPLACED); intentFilter1.addAction(Intent.ACTION_PACKAGE_REMOVED); intentFilter1.addDataScheme("package"); context.registerReceiver(updateInstallReceiver, intentFilter1); //注销 context.unregisterReceiver(updateInstallReceiver); //删除安装包 public static void clearUpdateApk(Context context, String filename){ File updateDir; File updateFile; if (Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { updateDir = new File(Environment.getExternalStorageDirectory(), UpdateInfo.updateDownloadDir); } else { updateDir = context.getFilesDir(); } updateFile = new File(updateDir.getPath(),filename + ".apk"); if (updateFile.exists()) { UpdateUtils.print("Update: delete update apk"); boolean cls = updateFile.delete(); Toast.makeText(context, String.format("%s.apk is deleted", filename), Toast.LENGTH_LONG).show(); } else { UpdateUtils.print("Update: no update apk to delete"); } }