android - 如何检查 Activity 是在前台还是在可见背景中?

我在计时器上有一个启动画面。我的问题是,在我 finish() 我的 Activity 之前,我需要检查下一个 Activity 是否已经开始,因为会弹出一个系统对话框,我只想 finish();一旦用户从对话框中选择了一个选项?

我知道关于如何查看您的 Activity 是否在前台有很多问题,但我不知道这是否也允许在 Activity 顶部出现对话框。

这是问题所在,红色是我的 Activity ,它在后台,而对话在前台:

编辑:我试过不使用 finish() 但我的 Activity 可以回到我试图避免的应用程序堆栈中。

最佳答案

这是推荐的正确解决方案:

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() 来检查 Activity 是否可见。在那里,您还可以检查用户是否选择了一个选项。满足两个条件时继续。

消息来源还提到了两个错误的解决方案......所以避免这样做。

来源:stackoverflow

https://stackoverflow.com/questions/18038399/

相关文章:

android - 如何调试签署发布的apk?

android - 带有完成操作按钮的多行 EditText

android - 无法修改 ListView 中的 ArrayAdapter : Unsuppor

android - 带有阴影的自定义 ImageView

android - 获取 backstack 中的最新 fragment

android - ListView addHeaderView 导致位置加一?

android - ViewPager.setOffscreenPageLimit(0) 无法按预期

android - SearchView 的 OnCloseListener 不起作用

android - 清算 Intent

android - 如何将值从一个 Activity 传递到上一个 Activity