欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

判断Android程序是否在前台运行的两种方法

程序员文章站 2023-10-28 20:09:28
@override protected void onstop() { if (!isapponforeground()) { debug....
@override 
protected void onstop() { 
  if (!isapponforeground()) { 
    debug.i("dwy", "enter background"); 
    misbackground = true; 
  } else { 
    debug.i("dwy", "foreground"); 
    misbackground = false; 
  } 

judge is app in background when onstop() get called.

public boolean isapponforeground() { 
    // returns a list of application processes that are running on the 
    // device 
 
    activitymanager activitymanager = (activitymanager) getapplicationcontext().getsystemservice(context.activity_service); 
    string packagename = getapplicationcontext().getpackagename(); 
 
    list<activitymanager.runningappprocessinfo> appprocesses = activitymanager 
        .getrunningappprocesses(); 
    if (appprocesses == null) 
      return false; 
 
    for (activitymanager.runningappprocessinfo appprocess : appprocesses) { 
      // the name of the process that this object is associated with. 
      if (appprocess.processname.equals(packagename) 
          && appprocess.importance == activitymanager.runningappprocessinfo.importance_foreground) { 
        return true; 
      } 
    } 
    return false; 
  } 


方法二:

/** 
  * 需要权限:android.permission.get_tasks 
  * 
  * @param context 
  * @return 
  */ 
  public boolean isapplicationbroughttobackground(context context) { 
    activitymanager am = (activitymanager) context 
            .getsystemservice(context.activity_service); 
    list<runningtaskinfo> tasks = am.getrunningtasks(1); 
    if (tasks != null && !tasks.isempty()) { 
      componentname topactivity = tasks.get(0).topactivity; 
      debug.i(tag, "topactivity:" + topactivity.flattentostring()); 
      debug.f(tag, "topactivity:" + topactivity.flattentostring()); 
      if (!topactivity.getpackagename().equals(context.getpackagename())) { 
        return true; 
      } 
    } 
    return false; 
  }