package com.secspace.lib.common.utils;

import android.app.ActivityManager;
import android.content.Context;

import com.secspace.lib.common.compat.BuildCompat;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

public class ReflectAmsUtil {
    public static List<ActivityManager.RecentTaskInfo> getRecentTasks(Context context, int maxNum, int flags) throws Exception {
        ActivityManager ams = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        Method method = Class.forName("android.app.ActivityManager").getMethod("getRecentTasks", int.class, int.class);
        return (List<ActivityManager.RecentTaskInfo>) method.invoke(ams, maxNum, flags);
    }

    public static void removeTask(Context context, int taskId) throws Exception {
        ActivityManager ams = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (BuildCompat.isPie()) {
            Class<?> activityManager = Class.forName("android.app.ActivityManager");
            Field field = activityManager.getDeclaredField("IActivityManagerSingleton");
            field.setAccessible(true);
            Object singleton = field.get(null);
            Method get = Class.forName("android.util.Singleton").getMethod("get", new Class[]{});
            Object binder = get.invoke(singleton, new Object[]{});
            Class<?> iActivityManager = Class.forName("android.app.IActivityManager");
            Method removeTask = iActivityManager.getMethod("removeTask", int.class);
            removeTask.invoke(binder, taskId);
        } else {
            Class<?> activityManager = Class.forName("android.app.ActivityManager");
            Method removeTask = activityManager.getMethod("removeTask", int.class);
            removeTask.invoke(ams, taskId);
        }
    }

    public static List<ActivityManager.RunningTaskInfo> getRunningTasks(Context context, int max) throws Exception {
        ActivityManager ams = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        return ams.getRunningTasks(max);
    }

    public static List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses(Context context) throws Exception {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        return manager.getRunningAppProcesses();
    }

}
