Android ActivityManager使用案例详解

  //判断应用是否在前台运行

  public boolean isRunningForeground(Context context){

  String packageName=getPackageName(context);

  String topActivityClassName=getTopActivityName(context);

  System.out.println("packageName="+packageName+",topActivityClassName="+topActivityClassName);

  if (packageName!=null&&topActivityClassName!=null&&topActivityClassName.startsWith(packageName)) {

  System.out.println("应用在前台执行");

  return true;

  } else {

  System.out.println("应用在后台执行");

  return false;

  }

  }

  // 判断应用是否在运行

  public boolean isRun(Context context,String mPackageName){

  ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);

  List list = am.getRunningTasks(100);

  boolean isAppRunning = false;

  //100表示取的最大的任务数,info.topActivity表示当前正在运行的Activity,info.baseActivity表示系统后台有此进程在运行

  for (RunningTaskInfo info : list) {

  if (info.topActivity.getPackageName().equals(mPackageName) || info.baseActivity.getPackageName().equals(mPackageName)) {

  isAppRunning = true;

  Log.i("ActivityService",info.topActivity.getPackageName() + " info.baseActivity.getPackageName()="+info.baseActivity.getPackageName());

  break;

  }

  }

  if(isAppRunning){

  Log.i("ActivityService", "该程序正在运行");

  }else{

  Log.i("ActivityService", "该程序没有运行");

  }

  return isAppRunning;

  }

  //获取栈顶ActivityName

  public String getTopActivityName(Context context){

  String topActivityClassName=null;

  ActivityManager activityManager =

  (ActivityManager)(context.getSystemService(android.content.Context.ACTIVITY_SERVICE )) ;

  List runningTaskInfos = activityManager.getRunningTasks(1) ;

  if(runningTaskInfos != null){

  ComponentName f=runningTaskInfos.get(0).topActivity;

  topActivityClassName=f.getClassName();

  }

  return topActivityClassName;

  }

  public String getPackageName(Context context){

  String packageName = context.getPackageName();

  return packageName;

  }