注册 登录
  • 欢迎访问Sharezer Blog

Android 移除最近任务

Android sharezer 1233次浏览 已收录 0个评论

权限

必须是一个系统app,增加以下权限:

<uses-permission android:name="android.permission.REAL_GET_TASKS" />
<uses-permission android:name="android.permission.REMOVE_TASKS"/>
<uses-permission android:name="android.permission.REORDER_TASKS"/>

代码

/**
* 移除最近任务
*
* @param taskId
*/
public void removeTask(int taskId) {
   Log.d(TAG, "removeTask: " + taskId);
   ActivityManager am = (ActivityManager) theContext.getSystemService(Context.ACTIVITY_SERVICE);
   try {
       Class<?> activityManagerClass = Class.forName("android.app.ActivityManager");
       Method removeTask = activityManagerClass.getDeclaredMethod("removeTask", int.class);
       removeTask.setAccessible(true);
       removeTask.invoke(am, taskId);
   } catch (ClassNotFoundException e) {
       Log.i(TAG, "No Such Class Found Exception", e);
   } catch (Exception e) {
       Log.i(TAG, "General Exception occurred", e);
   }
}

/**
* 通过包名清理任务
* @param packageName 包名
*/
public void clearRecentTaskByPackageName(String packageName) {
   if (theContext == null) return;

   List<ActivityManager.RunningTaskInfo> mRunningTasks = null;
   try {
       mRunningTasks = ActivityManagerNative.getDefault().getTasks(MAX_RECENT_TASKS, 0); //30表示获取的最大数
   } catch (RemoteException e) {
       e.printStackTrace();
   }
   for (ActivityManager.RunningTaskInfo amTask : mRunningTasks) {
       if (packageName.contentEquals(amTask.baseActivity.getPackageName())) {
           removeTask(amTask.id);
       }
   }
}

/**
* 清理没有正在运行的任务
*/
public void clearRecentListByUnused() {
   List<Integer> taskIdList = new ArrayList<>();
   List<ActivityManager.RunningTaskInfo> runningTasks = null;

   try {
       runningTasks = ActivityManagerNative.getDefault().getTasks(MAX_RECENT_TASKS, 0);
   } catch (RemoteException e) {
       e.printStackTrace();
   }

   for (ActivityManager.RunningTaskInfo amTask : runningTasks) {
       taskIdList.add(amTask.id);
       Log.d("TaskInfo", amTask.baseActivity.getPackageName() + "(" + amTask.id + ")");
   }

   ActivityManager am = (ActivityManager) theContext.getSystemService(Context.ACTIVITY_SERVICE);
   List<ActivityManager.RecentTaskInfo> recentTasks = am.getRecentTasks(MAX_RECENT_TASKS, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
   for (int i = 0; i < recentTasks.size(); ++i) {
       ActivityManager.RecentTaskInfo info = recentTasks.get(i);

       if(info.id == -1 || !taskIdList.contains(info.persistentId))
           removeTask(info.persistentId);
   }
}


Sharezer , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明Android 移除最近任务
喜欢 (0)
[liangshaoze@sina.cn]
分享 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址