android – 如何检查活动是否在前景或可见背景?

我有一个启动屏幕上的计时器。我的问题是,在我完成()我的活动,我需要检查下一个活动已经开始,因为一个系统对话框弹出,我只想完成();一旦用户从对话框中选择了一个选项?

我知道有很多问题,如何看看你的活动是否在前台,但我不知道这是否允许对话框上的活动。

这里是问题,红色是我的活动是在后台,而对话是在前台:

编辑:我试过只是不使用finish(),但我的活动可以回到我想避免的应用程序堆栈。

这是建议作为正确的解决方案:

The right solution (credits go to Dan, CommonsWare and NeTeInStEiN)
Track visibility of your application by yourself using
Activity.onPause, Activity.onResume methods. Store “visibility” status
in some other class. Good choices are your own implementation of the
Application or a Service (there are also a few variations of this
solution if you’d like to check activity visibility from the service).

Example
Implement custom Application class (note the isActivityVisible() static method):

public class MyApplication extends Application {

  public static boolean isActivityVisible() {
    return activityVisible;
  }  

  public static void activityResumed() {
    activityVisible = true;
  }

  public static void activityPaused() {
    activityVisible = false;
  }

  private static boolean activityVisible;
}

Register your application class in AndroidManifest.xml:

<application
    android:name="your.app.package.MyApplication"
    android:icon="@drawable/icon"
    android:label="@string/app_name" >

Add onPause and onResume to every Activity in the project (you may
create a common ancestor for your Activities if you’d like to, but if
your activity is already extended from MapActivity/ListActivity etc.
you still need to write the following by hand):

@Override
protected void onResume() {
  super.onResume();
  MyApplication.activityResumed();
}

@Override
protected void onPause() {
  super.onPause();
  MyApplication.activityPaused();
}

在finish()方法中,您想要使用isActivityVisible()来检查活动是否可见。在那里你还可以检查用户是否选择了一个选项。当两个条件都满足时继续。

源还提到两个错误的解决方案…所以避免这样做。

资料来源:stackoverflow

http://stackoverflow.com/questions/18038399/how-to-check-if-activity-is-in-foreground-or-in-visible-background

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:android – 如何检查活动是否在前景或可见背景?