publicclassWatchDogKiller{ privatestaticfinal String TAG = "WatchDogKiller"; privatestaticvolatileboolean sWatchdogStopped = false;
publicstaticbooleancheckWatchDogAlive(){ final Class clazz; try { clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon"); final Field field = clazz.getDeclaredField("INSTANCE"); field.setAccessible(true); final Object watchdog = field.get(null); Method isRunningMethod = clazz.getSuperclass().getDeclaredMethod("isRunning"); isRunningMethod.setAccessible(true); boolean isRunning = (boolean) isRunningMethod.invoke(watchdog); return isRunning; } catch (Exception e) { e.printStackTrace(); } returnfalse; }
publicstaticvoidstopWatchDog(){ // 建议在在debug包或者灰度包中不要stop,保留发现问题的能力。 if (!BuildConfig.DEBUG) { return; }
// Android P 以后不能反射FinalizerWatchdogDaemon if (Build.VERSION.SDK_INT >= 28) { Log.w(TAG, "stopWatchDog, do not support after Android P, just return"); return; } if (sWatchdogStopped) { Log.w(TAG, "stopWatchDog, already stopped, just return"); return; } sWatchdogStopped = true; Log.w(TAG, "stopWatchDog, try to stop watchdog");
try { final Class clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon"); final Field field = clazz.getDeclaredField("INSTANCE"); field.setAccessible(true); final Object watchdog = field.get(null); try { final Field thread = clazz.getSuperclass().getDeclaredField("thread"); thread.setAccessible(true); thread.set(watchdog, null); } catch (final Throwable t) { Log.e(TAG, "stopWatchDog, set null occur error:" + t);