@RequiresApi(api = Build.VERSION_CODES.M)
public static void clearRecentApps() {
ActivityManager mActivityManager;
Method mRemoveTask;
try {
Class<?> ActivityThread = Class.forName("android.app.ActivityThread");
Method method = ActivityThread.getMethod("currentActivityThread");
Object currentActivityThread = method.invoke(ActivityThread);
Method method2 = currentActivityThread.getClass().getMethod("getApplication");
Context contextInstance = (Context) method2.invoke(currentActivityThread);
Class<?> activityManagerClass = Class.forName("android.app.ActivityManager");
mActivityManager = (ActivityManager) contextInstance.getSystemService(Context.ACTIVITY_SERVICE);
print("Clear all recent tasks!!");
mRemoveTask = activityManagerClass.getMethod("removeTask", int.class);
mRemoveTask.setAccessible(true);
List<ActivityManager.RecentTaskInfo> recents =
mActivityManager.getRecentTasks(Integer.MAX_VALUE, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
for (ActivityManager.RecentTaskInfo recent: recents) {
ComponentName cn = recent.baseActivity;
if (cn == null) continue;
String pkg = cn.getPackageName();
if (pkg.contains("launcher")) continue;
print("--> Clear activity \"%s\"", pkg);
mRemoveTask.invoke(mActivityManager, recent.persistentId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
该方法在android P之前有效,但是android p无效,我查看了android P的源代码,class activitymanager删除了API“ removeTask”,所以我想知道另一种选择吗?我尝试了“列出appTasks = mActivityManager.getAppTasks();”