Android determines whether an instance of Activity is running in the foreground

  • 2021-08-28 21:18:49
  • OfStack

As shown below:


  /**
   *  Determine whether an interface is in the foreground 
   *
   * @param context  Context
   * @param className  Class name of interface 
   * @return  Is it displayed in the foreground 
   */
  public static boolean isForeground(Context context, String className) {
    if (context == null || TextUtils.isEmpty(className))
      return false;
    ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
//    boolean flag=false;
    for (ActivityManager.RunningTaskInfo taskInfo : list) {
      if (taskInfo.topActivity.getShortClassName().contains(className)) { //  It means that it has been started 
//        flag = true;
        return true;
      }
    }
    return false;
  }

    if(TCPHandle.isForeground(HomeActivity.this,"EvaluateForHandActivity")||TCPHandle.isForeground(HomeActivity.this,"EvaluateActivity"))
    {
      return;
    }

Related articles: