android 7和8可以采用反射调用ActivityManager中的removeTask方法,网上搜文章大部分都是采用这种实现
removeTask代码地址
http://www.aospxref.com/android-7.1.2_r39/xref/frameworks/base/core/java/android/app/ActivityManager.java#1873
http://www.aospxref.com/android-8.0.0_r36/xref/frameworks/base/core/java/android/app/ActivityManager.java#2127
如下是ActivityManager.java中removeTask的实现。
public boolean removeTask(int taskId) throws SecurityException {
try {
return getService().removeTask(taskId);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
通过对比发现他是调用的IActivityManager接口里面的removeTask方法,虽然ActivityManager移除了removeTask方法,但是在高版本里面的IActivityManager还是保留了
@UnsupportedAppUsage
boolean removeTask(int var1) throws RemoteException;
那么我们可以直接反射IActivityManager并调用里面removeTask方法,最终解决方便如下
public static void clearRecent(Context context) {
try {
ActivityManager tasksManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
Method method = tasksManager.getClass().getMethod("getService");
method.setAccessible(true);
IActivityManager getService = (IActivityManager) method.invoke(tasksManager);
final List<ActivityManager.RecentTaskInfo> recentTasks = tasksManager.getRecentTasks(Integer.MAX_VALUE, PackageManager.MATCH_ALL);
for (ActivityManager.RecentTaskInfo recentTask : recentTasks) {
if (recentTask != null) {
int taskId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q ? recentTask.taskId : recentTask.persistentId;
getService.removeTask(taskId);
Log.e(TAG, "一切都结束了:" + recentTask + " " + taskId);
}
}
} catch (Exception e) {
Log.e(TAG, "发生异常:");
e.printStackTrace();
}
}
getService源码地址
http://www.aospxref.com/android-9.0.0_r61/xref/frameworks/base/core/java/android/app/ActivityManager.java#4125
http://www.aospxref.com/android-10.0.0_r47/xref/frameworks/base/core/java/android/app/ActivityManager.java#4041
http://www.aospxref.com/android-11.0.0_r21/xref/frameworks/base/core/java/android/app/ActivityManager.java#4545
https://www.aospxref.com/android-12.0.0_r3/xref/frameworks/base/core/java/android/app/ActivityManager.java#4340