检查Android应用程序是否位于前台的最佳方法是什么?

时间:2012-02-01 10:50:32

标签: android

我有一个使用AsyncTasks对服务器进行REST调用的应用程序。每当AsyncTask完成时,它都会:显示错误对话框/调用下一个活动(如果应用程序在前台)或什么也不做(应用程序在后台)。

我这样做是为了避免在将应用程序发送到后台后弹出一个活动。

我见过一些实现:

  1. check android application is in foreground or not?
  2. Determining the current foreground application from a background task or service
  3. 目前我正在使用另一种,甚至更简单:

    • onResume of each activity我将全局变量设置为FOREGROUND
    • onPause每个活动我将全局变量设置为BACKGROUND

    你会推荐哪一个?

    PS 我知道这个视频https://www.youtube.com/watch?v=xHXn3Kg2IQE&list=PL73AA672847DC7B35中描述的REST调用的最佳实践,在我的具体情况下,这种方法似乎更合适。

2 个答案:

答案 0 :(得分:7)

private boolean isAppForground() {

        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> l = mActivityManager
                .getRunningAppProcesses();
        Iterator<RunningAppProcessInfo> i = l.iterator();
        while (i.hasNext()) {
            RunningAppProcessInfo info = i.next();

            if (info.uid == getApplicationInfo().uid && info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) 
                {
                    return true;
               }
           }
        return false;
    }

答案 1 :(得分:2)

我最终得到一个静态变量,每个Activity在onResume设置为true,在onPause设置为false。

在所有其他活动扩展的活动中添加了这些方法

    public abstract class AbstractActivity extends Activity 
    {

     private static boolean isInForeground = false;

     @Override
      protected void onResume()
     {
        super.onResume();
        isInForeground = true;
    }


    @Override
    protected void onPause()
    {
        super.onPause();
        isInForeground  = false;
    }

 }

了解工作原理Activity side-by-side lifecycle

如果 MY APP 位于前台或后台,我们会向您提供相关信息。

但Shailendra Rajawat仍然是更标准的选择......因为这有一些弱点:

  1. 只知道我自己的应用程序是在前景还是背景
  2. 如果您有透明活动,则无法使用。因为生命周期不一样,所以在启动透明活动时不会调用onPause / onStop。