Android How to - Get Class name of top activity








Question

We would like to know how to get Class name of top activity.

Answer

//  w ww. j a  v  a  2  s  . co  m
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
public class Main{
  /**
   * Returns Class name of top activity
   * @param context Context to provide activity information
   * @return String representing class name of top activity
   */
  public static String getTopActivityClassName(Context context) {
    ComponentName activity = getTopActivity(context);
    if (activity == null) {
      return null;
    }
    return activity.getClassName();
  }
  private static ComponentName getTopActivity(Context context) {
    ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
    if (am == null) {
      return null;
    }
    List<RunningTaskInfo> info = am.getRunningTasks(1);
    if (info == null) {
      return null;
    }
    ComponentName activity = info.get(0).topActivity;
    return activity;
  }
}