【问题标题】:What the best way to check if an Android application is in foreground?检查 Android 应用程序是否在前台的最佳方法是什么?
【发布时间】:2012-02-01 10:50:32
【问题描述】:

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

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

我见过一些实现:

  1. check android application is in foreground or not?
  2. Determining the current foreground application from a background task or service

目前我正在使用另一个更简单的方法:

  • 每个活动的 onResume 我都设置了一个全局变量为 FOREGROUND
  • 每个活动的 onPause 我将一个全局变量设置为背景

你会推荐哪个?

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

【问题讨论】:

    标签: android


    【解决方案1】:
    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;
        }
    

    【讨论】:

    • 即使您的应用在内存中打开,它也会返回 true。
    【解决方案2】:

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

    在所有其他 Activity 扩展的 Activity 上添加了这些方法

        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. 它只适用于知道 MY OWN 应用程序是在前台还是后台
    2. 如果您有透明的活动,它就不起作用。因为生命周期不一样,所以在启动透明 Activity 时不会调用 onPause/onStop。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2016-09-21
      • 2011-11-20
      • 2011-05-25
      相关资源
      最近更新 更多