让对象监听 Activity 生命周期事件?
我编写的类之一需要在发生以下 Activity
事件时做出反应:
- onStart()
- onPause()
- onResume()
- onStop()
本身的事件做出反应:
public class Activity extends ApplicationContext
{
protected void onCreate(Bundle savedInstanceState);
protected void onStart();
protected void onRestart();
protected void onResume();
protected void onPause();
protected void onStop();
protected void onDestroy();
}
我可以对Activity code>Activity 我可以告诉相关对象发生了某个事件,但我不喜欢这个想法:它要求开发人员在我的 object/class
之外实现逻辑。理想情况下,我希望该对象负责注册这些事件并将其自身设置为侦听器,独立于 Activity
。
有什么想法吗?提前致谢。
One of the classes I've written needs to react when the following Activity
events occur:
- onStart()
- onPause()
- onResume()
- onStop()
I can react to those on the Activity itself:
public class Activity extends ApplicationContext
{
protected void onCreate(Bundle savedInstanceState);
protected void onStart();
protected void onRestart();
protected void onResume();
protected void onPause();
protected void onStop();
protected void onDestroy();
}
From the Activity
I could tell the object in question that a certain event has occurred, but I don't like this idea: it requires the developer to implement the logic outside my object/class
. Ideally I would like the object to be responsible for registering these events and set itself as a listener, independent of the Activity
.
Any ideas? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
API 级别 14 有 Application.ActivityLifecycleCallbacks。
在此之前,抱歉,没有。
如果您希望将您的类提供给其他人,您将需要提供扩展最常见活动的抽象类,或者让他们在自己的活动生命周期方法中进行某些调用,例如
也可以使其更通用,并创建抽象类接受 NotifyingActivity.LifecycleListener 的 NotifyingActivity 类,并使您的类实现此类侦听器并在其构造函数中注册自身。
API level 14 has Application.ActivityLifecycleCallbacks.
Before that, afaik, sorry, no.
If you wish to offer your class to others, you will need to either provide abstract classes that extend the most common Activities, or have them put certain calls in their own Activity's lifecycle methods, like
May as well make it more general, and create abstract NotifyingActivity classes that accept NotifyingActivity.LifecycleListener's, and make your class implement such a listener and register itself in its constructor.
利用自 API 级别 14 以来引入的 ActivityLifecycleCallbacks。
这就是界面看起来像现在这样。
您需要做的只是实现接口方法并将其注册到您的应用程序上。
Leverage ActivityLifecycleCallbacks that has been introduced since API level 14.
This is what the interface looks like now.
What you need to do is simply to implement the interface methods and register it on your application.
您可以使用 这个库 来完成您想要做的事情,而无需编写代码在您的活动或基本活动中。
而且使用起来非常简单:
也许它可以帮助某人
You can use this library that does exactly what you're trying to do, without having to write code in your activity or in your base activity.
And is very simple to use:
Maybe it helps someone