Android How to - Is App Running on Top








Question

We would like to know how to is App Running on Top.

Answer

import java.util.List;
//from  w  w w.ja  v  a 2  s .c  om
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;

public class Main {
  public static boolean isAppRunningTop(Context context) {
    
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> list = am.getRunningTasks(1);
    if (list.size() > 0) {
      String packageName = context.getPackageName();
      RunningTaskInfo topRunningTaskinfo  = list.get(0);
      if (topRunningTaskinfo.topActivity.getPackageName().equals(packageName)) {
        return true;
      }
    }

    return false;
  }

}