如何检查 activity 是否为 运行?

How to check if any activity is running?

我想处理用户点击 GCM 通知的行为。我想在两种情况下以不同的方式处理它:应用程序不是 运行(堆栈中没有前台和后台活动)并且应用程序是 运行 并且至少有一个 activity 在堆栈中。我该怎么做?

在我的 senario 中,我更改了 NotificationReciever。 在来自 ParsePushBroadcastReceiver 的 "onPushReceive" 方法中。 (我使用解析进行推送)。在您的 senario whre 中检测通知接收。

   ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> services = activityManager
                    .getRunningTasks(Integer.MAX_VALUE);
            boolean isActivityFound = false;

            if (services.get(0).topActivity.getPackageName()
                    .equalsIgnoreCase(context.getPackageName())) {
                isActivityFound = true;
            }

            if (isActivityFound) {
                //app is running
             return;
            } else {
                // applicaiton is not open, notification can come
                super.onPushReceive(context, intent);
            }

使用经典方法在 Activity.

中定义一个 static 变量
class MyActivity extends FragmentActivity {
     static boolean isActive = false;

      @Override
      public void onStart() {
         super.onStart();
         isActive = true;
      } 

      @Override
      public void onStop() {
         super.onStop();
         isActive = false;
      }
}

Determining if your Android Application is in Background or Foreground is the most reliable method that I have come across. As explained in that article and elsewhere there are lot's of different ways for doing this, but using Application.ActivityLifecycleCallbacks 所描述的通常是非常可靠的。它会记录启动的活动数量,如果数量大于 1,则您的应用程序在前台。