Android应用,活动状态(正在运行,未运行,前景/背景)

Atu*_*lic 9 android activity-lifecycle android-activity android-task

我遇到了一个要求,但我无法得到正确的实施方式,因此需要你的帮助.

我想做的事? - 我想根据我得到的通知执行操作如下:

  1. 当应用程序打开并处于前台时,即用户可见,我收到通知,我只需显示一个弹出窗口即可启动我的活动B.
  2. 当应用程序关闭时,即无论是在后台还是在前台,我都会收到通知,我将首先启动我的应用程序然后启动活动B.
  3. 当应用程序在后台运行时,即在最近但用户不可见时,我想启动我的活动B而不重新启动应用程序.此外,在这种情况下,当用户按下活动B时,他们应该在将其发送到后台之前看到他们停止的屏幕.

我做了什么?我已经取得了第一点和第二点.我想达到第3点.我试过以下

public static boolean isApplicationBroughtToBackground(final Activity activity) {
  ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
  List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(1);

  // Check the top Activity against the list of Activities contained in the Application's package.
  if (!tasks.isEmpty()) {
    ComponentName topActivity = tasks.get(0).topActivity;
    try {
      PackageInfo pi = activity.getPackageManager().getPackageInfo(activity.getPackageName(), PackageManager.GET_ACTIVITIES);
      for (ActivityInfo activityInfo : pi.activities) {
        if(topActivity.getClassName().equals(activityInfo.name)) {
          return false;
        }
      }
    } catch( PackageManager.NameNotFoundException e) {
      return false; // Never happens.
    }
  }
  return true;
}
Run Code Online (Sandbox Code Playgroud)

然而,在两种情况下,#2和#3都返回true,所以我无法仅区分#3.

我也在每个活动中尝试过以下操作,

@Override
protected void onPause() {
    super.onPause();
    saveIsPausedInPref(true);
}

@Override
protected void onResume() {
    super.onResume();
    saveIsPausedInPref(false);
}   
Run Code Online (Sandbox Code Playgroud)

但是,如果通过按主页按钮将应用程序发送到后台,它也没有给出所需的结果我的首选项将具有isPaused = true,如果用户从最近删除该应用程序,那么它将保持真实并且我将不再能够在通知到达时区分点#2和#3.

为整个故事道歉,但我希望我能够解释我的要求.

提前致谢.:)

编辑:

        <activity
            android:name=".HomeActivity"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name=".ChatProfileActivity"
            android:screenOrientation="portrait" >
        </activity>
Run Code Online (Sandbox Code Playgroud)

Dav*_*ser 2

要区分情况 #2 和情况 #3,您可以执行以下操作:

ActivityB如果不是情况 #1,则启动。这样做ActivityB.onCreate()

super.onCreate(...);
if (isTaskRoot()) {
    // ActivityB has been started when the app is not running,
    //  start the app from the beginning
    Intent restartIntent = new Intent(this, MyRootActivity.class);
    startActivity(restartIntent);
    finish();
    return;
}
... rest of onCreate() code here...
Run Code Online (Sandbox Code Playgroud)