如何检测我的任何活动是否位于最前面并且对用户可见? [英] How to detect if any of my activity is front-most and visible to user?
问题描述
我想在我的任何活动可见时启动一个意图,否则我会将其作为通知发布,并且会被用户触发.
I would like to launch an intent when any of my activity is visible, otherwise I will put it up as a notification, and will be fired by the user.
要确定这一点,我需要知道我的任何活动是否位于最前面,我该怎么做?
To decide this, I need to know if any of my activity is front-most, how do I that?
推荐答案
我不知道有没有一种方法可以获取当前显示的活动,但是您可以结合 Activity Lifecycle 和一个标志.
I don't know that there's a method to get the currently displayed activity, but you could do something combining the Activity Lifecycle and a flag.
对于标志,如果您扩展了 Application 类,这可能是一个不错的存储位置.为了扩展应用程序类,这个问题的最佳答案有信息.(d).
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 has info. (d).
因此可能会根据您想要的行为在 onResume/onPause 或 onStart/onStop 中跟踪当前的活动活动(或活动可见的标志).
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.
由于您有多个活动,因此您需要一个质心位置来存储标志,这就是应用程序有意义的原因.您可以通过转换应用程序上下文来获取自定义 Application 对象(例如 ((MyApplication)getApplicationContext()).isMyActivityActive).
Since you have multiple activities, you'll need a centroid place for storing the flag, which is why the Application makes sense. You can get the custom Application object by casting the application context (e.g. ((MyApplication)getApplicationContext()).isMyActivityActive).
您也可以扩展 Activity 以帮助保持此代码的整洁和包含.
You could extend Activity as well to help keep this code clean and contained.
如果您正在使用服务,则可以在 onStart/onStop(或 onResume/onPause)中的每个活动中绑定到该服务.如果绑定,您就可见.
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.
这篇关于如何检测我的任何活动是否位于最前面并且对用户可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!