Android:如何检查活动是否正在运行? [英] Android: how do I check if activity is running?

查看:36
本文介绍了Android:如何检查活动是否正在运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何简单的方法可以确定某个活动是否处于活动状态?我想根据活跃的活动做某些事情.例如:

Is there any simple way of determining whether or not a certain activity is active? I want to do certain things depending on which activity is active. eg:

if(activityrunning == activity1)
//do this
else if (activityrunning == activity2)
//do something else

推荐答案

您可以在活动中使用 static 变量.

You can use a static variable within the activity.

class MyActivity extends Activity {
     static boolean active = false;

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

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

唯一的问题是,如果您在两个相互链接的活动中使用它,那么有时会在第二个 onStart 之后调用第一个上的 onStop.所以两者都可能是正确的.

The only gotcha is that if you use it in two activities that link to each other then onStop on the first is sometimes called after onStart in second. So both might be true briefly.

取决于您尝试执行的操作(从服务更新当前活动?).您可以在您的活动 onStart 方法中的服务中注册一个静态侦听器,然后当您的服务想要更新 UI 时,正确的侦听器将可用.

Depending on what you are trying to do (update the current activity from a service?). You could just register a static listener in the service in your activity onStart method then the correct listener will be available when your service wants to update the UI.

这篇关于Android:如何检查活动是否正在运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆