get Task Packname - Android Android OS

Android examples for Android OS:Process

Description

get Task Packname

Demo Code


//package com.java2s;

import android.app.ActivityManager;

import android.content.Context;

import android.os.Build;

import android.util.Log;
import java.lang.reflect.Field;
import java.util.List;

public class Main {

    public static String getTaskPackname(Context context) {
        ActivityManager.RunningAppProcessInfo currentInfo = null;
        Field field = null;/*from   w  ww  . j a va2  s  . c  om*/
        int START_TASK_TO_FRONT = 2;
        String currentApp = "CurrentNULL";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                field = ActivityManager.RunningAppProcessInfo.class
                        .getDeclaredField("processState");
            } catch (Exception e) {
                e.printStackTrace();
            }
            ActivityManager am = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> appList = am
                    .getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo app : appList) {
                if (app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    Integer state = null;
                    try {
                        assert field != null;
                        state = field.getInt(app);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (state != null && state == START_TASK_TO_FRONT) {
                        currentInfo = app;
                        break;
                    }
                }
            }
            if (currentInfo != null) {
                currentApp = currentInfo.processName;
            }
        } else {
            ActivityManager am = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> tasks = am
                    .getRunningAppProcesses();
            currentApp = tasks.get(0).processName;
        }
        return currentApp;
    }
}

Related Tutorials