Android examples for android.content.pm:PackageManager
get Top App Info Package Name
import java.lang.reflect.Field; import java.util.List; import android.app.ActivityManager; import android.content.Context; import android.os.Build; public class Main { public static String getTopAppInfoPackageName(Context context) { if (Build.VERSION.SDK_INT < 21) { ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningTaskInfo> runningTasks = manager.getRunningTasks(1); if (runningTasks != null && runningTasks.size() > 0) { return runningTasks.get(0).topActivity.getPackageName(); } else {/*w ww. j a va 2 s .c o m*/ return ""; } } else { final int PROCESS_STATE_TOP = 2; try { Field processStateField = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState"); List<ActivityManager.RunningAppProcessInfo> processes = ((ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE)).getRunningAppProcesses(); for (ActivityManager.RunningAppProcessInfo process : processes) { if (process.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && process.importanceReasonCode == 0) { int state = processStateField.getInt(process); if (state == PROCESS_STATE_TOP) { String[] packname = process.pkgList; return packname[0]; } } } } catch (Exception e) { e.printStackTrace(); } return ""; } } }