Android关于apk安装成功广播监听

有这样的应用场景,apk安装成功后需要重启APP,就需要监听完成安装的回调或者广播


      
        
        
        
      
    

public class UpdateReceiver extends BroadcastReceiver {
  private static final String TAG = "UpdateReceiver";

  @Override public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (Intent.ACTION_PACKAGE_REPLACED.equals(action) || Intent.ACTION_MY_PACKAGE_REPLACED.equals(
        action)) {
      try {
        String scheme = intent.getScheme();
        String packageName = intent.getData().getSchemeSpecificPart();
        if (context.getPackageName().equals(packageName)) {
          Toast.makeText(context, "成功升级新版本!", Toast.LENGTH_SHORT).show();
          Intent intent1 = new Intent(context, FlashActivity.class);
          intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          context.startActivity(intent1);
        }
        LogMgr.d(TAG, "收到 ACTION_PACKAGE_REPLACED");
        LogMgr.d(TAG, " scheme=" + scheme);
        LogMgr.d(TAG, " schemeSpecificPart=" + packageName);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
}

这里提供一个在开发过程中用到的一个静默安装的方法,不一定适用于所有的设备:

public static void silentInstallApkByReflect(String apkPath) {
    PackageManager packageManager = ContextUtils.getContext().getPackageManager();
    Class pmClz = packageManager.getClass();
    try {
      if (Build.VERSION.SDK_INT >= 21) {
        Class aClass = Class.forName("android.app.PackageInstallObserver");
        Constructor constructor = aClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        Object installObserver = constructor.newInstance();
        Method method =
            pmClz.getDeclaredMethod("installPackage", Uri.class, aClass, int.class, String.class);
        method.setAccessible(true);
        method.invoke(packageManager, Uri.fromFile(new File(apkPath)), installObserver, 2, null);
      } else {
        Method method = pmClz.getDeclaredMethod("installPackage", Uri.class,
            Class.forName("android.content.pm.IPackageInstallObserver"), int.class, String.class);
        method.setAccessible(true);
        method.invoke(packageManager, Uri.fromFile(new File(apkPath)), null, 2, null);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

 

你可能感兴趣的:(Android关于apk安装成功广播监听)