如何在android中以编程方式关闭所有近期应用程序

时间:2016-04-20 10:13:08

标签: java android background-process

我正在设计一个删除最近任务的应用程序。我使用此代码删除最近的任务,

public boolean removeTask(int taskId, int flags) {
    try {
        return (Boolean) mRemoveTask.invoke(mActivityManager, Integer.valueOf(taskId), Integer.valueOf(flags) );
    } catch (Exception ex) {
        Log.i("MyActivityManager", "Task removal failed", ex);
    }
    return false;
}

public void clearRecentTasks() {
    List<ActivityManager.RecentTaskInfo> recents = mActivityManager.getRecentTasks(1000, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
    // Start from 1, since we don't want to kill ourselves!
    for( int i=1; i < recents.size(); i++ ) {
        removeTask( recents.get(i).persistentId, 0);
    }
}

1 个答案:

答案 0 :(得分:0)

Chaeck这一个:

private void killRunningApps(final Context context) {
    this.timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            List<String> packages = InstalledApps.getRunning(context);
            assert packages != null;
            for (String packageName : packages) {
                AppInfo info = InstalledApps.getAppInfo(packageName, context);
                assert info != null;
                if ((info.getFlag() & ApplicationInfo.FLAG_SYSTEM) == 1) continue;
                manager.killBackgroundProcesses(packageName);
            }
        }
    }, 0, this.updateInterval);
}

首先,你必须申报经理:

    private ActivityManager manager;
onCreate()中的

this.manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);