代码之家  ›  专栏  ›  技术社区  ›  Pentium10

如何检测我的任何活动是否是最前面的并且对用户可见?

  •  25
  • Pentium10  · 技术社区  · 15 年前

    当我的任何活动可见时,我想启动一个意图,否则我将把它作为一个通知,并由用户激发。

    要决定这一点,我需要知道我的任何一项活动是否是最重要的,我该怎么做?

    5 回复  |  直到 10 年前
        1
  •  10
  •   Community CDub    8 年前

    我不知道有一种方法可以获取当前显示的活动,但是可以将 Activity Lifecycle 一面旗帜。

    For the flag, if you've extended the Application class, that's probably a decent place to store it. For extending the application class, the top answer to this question 有信息。(d)。

    So probably keep track of the current active activity (or a flag that the activity is visible) in onResume/onPause or onStart/onStop depending on exactly what behavior you want.

    因为您有多个活动,所以需要一个质心位置来存储标志,这就是为什么应用程序有意义。您可以通过强制转换应用程序上下文(例如((myApplication)getApplicationContext()).ismyActivityActive)来获取自定义应用程序对象。

    您还可以扩展活动以帮助保持代码的整洁和包含性。


    If you're using a service you could bind to the service in every activity in the onStart/onStop (or onResume/onPause). If bound, you're visible.

        2
  •  4
  •   Zds    13 年前

    您可以从ActivityManager请求正在运行的任务:

    ActivityManager activityManager = (ActivityManager)getContext()
                    .getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> runningTasks = activityManager.getRunningTasks(Integer.MAX_VALUE));
    

    从API文档:

    返回当前正在运行的任务列表,其中 最近的是第一个,以后的是第一个。

    所以列表中的第一项是最前面的活动。

        3
  •  3
  •   yanchenko    15 年前

    onResume() 呼叫&& onPause() 未调用=可见。
    有一个 public static Activity currentlyVisible; 在你 Application 将由活动更新的子类(设置为中的实例) OnReSuMe() null 爱德华 OnPoAube() )或者发明一种不那么难看的注册表变体。

        4
  •  2
  •   Grant    14 年前

    You could use onWindowFocusChanged(boolean hasFocus) place this in a superclass of your activities to launch the intent if it has focus.

        5
  •  0
  •   Ankita    10 年前

    您可以通过代码来完成一个简单的技巧,而不是使用活动管理器。如果您仔细观察活动周期,两个活动和前台到后台的流程如下。假设A和B是两个活动。

    When transition from A to B: 1. onPause() of A is called 2. onResume() of B is called 3. onStop() of A is called when B is fully resumed

    当应用程序进入后台时:1.的onPause()称为2。调用的OnStop()。

    只需在活动中放置一个标志,就可以检测到您的后台事件。

    制作一个抽象的活动,并从其他活动中扩展它,这样您就不必在需要后台事件的任何地方复制粘贴所有其他活动的代码。

    在抽象活动中,创建标记isappinbackground。

    在onCreate()方法中:isAppinBackground=false;

    在onPause()方法中:isAppinBackground=false;

    在onstop()方法中:isappinbackground=true;

    如果isAppinBackground为真,则只需检查onResume()。 n检查标志后,再次设置isappinbackground=false

    对于两个活动之间的转换,因为第一个的onstop()将始终在第二个活动恢复后调用,标志永远不会为true,当应用程序处于后台时,将在onpause后立即调用活动的onstop(),因此稍后打开应用程序时,标志将为true。