首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检查Android应用程序是在后台运行还是在前台运行?

如何检查Android应用程序是在后台运行还是在前台运行?
EN

Stack Overflow用户
提问于 2017-05-04 18:03:49
回答 3查看 2K关注 0票数 1

例如,我在我的项目中有以下代码:

代码语言:javascript
复制
   public class Utilities extends Application
{
    private static int stateCounter;

    public void onCreate()
    {
        super.onCreate();
        stateCounter = 0;
    }

    /**
     * @return true if application is on background
     * */
    public static boolean isApplicationOnBackground()
    {
        return stateCounter == 0;
    }

    //to be called on each Activity onStart()
    public static void activityStarted()
    {
        stateCounter++;
    }

    //to be called on each Activity onStop()
    public static void activityStopped()
    {
        stateCounter--;
    } 
}

但在ios中检测状态很简单:

代码语言:javascript
复制
let state: UIApplicationState = UIApplication.sharedApplication().applicationState // or use  let state =  UIApplication.sharedApplication().applicationState

if state == .Background {

// background
}
else if state == .Active {

// foreground
}

我正在寻找android是否有其他解决方案来做这个测试?

EN

回答 3

Stack Overflow用户

发布于 2017-05-04 18:07:50

在应用程序类中编写此方法,并随心所欲地使用。

代码语言:javascript
复制
  public boolean isApplicationBroughtToBackground() {
    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(getPackageName())) {
            return true;
        }
    }
    return false;
}

创建一个新类baseActivity

代码语言:javascript
复制
public class BaseActivity extends AppCompatActivity {

static Boolean IsResumecalled = false;


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
protected void onResume() {
    super.onResume();
    if (!IsResumecalled) {
        //call api here
    IsResumecalled= true;
    }
}

@Override
protected void onStop() {
    super.onStop();
    if (Myapplication.getInstance().isApplicationBroughtToBackground()) {
      //call api here
       IsResumecalled= false;
    }
}

}

并使用BaseActivity为每个活动类进行扩展

票数 5
EN

Stack Overflow用户

发布于 2017-05-04 18:09:06

代码语言:javascript
复制
private boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null) {
            return false;
        }
        final String packageName = context.getPackageName();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            Log.d(TAG, "isAppOnForeground: " + appProcess.processName);
            if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }
}
票数 2
EN

Stack Overflow用户

发布于 2020-02-26 06:02:44

尝试使用LifecyclecurrentState方法。

代码语言:javascript
复制
public static boolean appIsOrWasInBackground() {
  Lifecycle.State currentState = ProcessLifecycleOwner.get().getLifecycle().getCurrentState();
  return currentState == Lifecycle.State.CREATED || currentState == Lifecycle.State.STARTED; // CREATED is when the app is currently in the background. STARTED is when the app is coming from the background, for example, from a `startActivity` call from a background Service or BroadcastReceiver. Either of these mean it _is_ or _was_ in the background (and should probably stay there).
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43779809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档