简体   繁体   English

Android:收听onDestroy()活动

[英]Android: Listening to activity onDestroy()

So, on Android, 因此,在Android上,
How can I listen to/subscribe to an Activity onDestroy() method? 如何收听/订阅Activity onDestroy()方法? I have a shared object/class/service that can be accessed and created through multiple activities but it needs to know when the caller activity is destroyed. 我有一个共享的对象/类/服务,可以通过多个活动来访问和创建共享的对象/类/服务,但是它需要知道何时调用者活动被销毁。

I can't modify the caller activities code, but I have a reference to the particular activity that is calling my class. 我无法修改呼叫者活动代码,但是我有一个对调用我的类的特定活动的引用。

So someActivity -> Creates my object 所以someActivity->创建我的对象
Object needs to know when that activity closes. 对象需要知道该活动何时关闭。

I assume you are trying to do something in the object you created using your activity, but somehow, if your activity is closed. 我假设您正在尝试使用活动创建的对象中执行某项操作,但是如果活动已关闭,则采用某种方式。 Then your object will crash if it try to access getActivity(). 如果您的对象尝试访问getActivity(),则会崩溃。

Assume your activity class name someActivity and your object is a fragment. 假设您的活动类名称为someActivity,而您的对象是一个片段。 Fragment provide you to use getActivity. Fragment提供您使用getActivity。 If the object you created not a fragment, then you probably has to find a way access it. 如果创建的对象不是片段,则可能必须找到一种访问它的方式。

someActivity activity = (someActivity) getActivity();
        if (activity != null && !activity.isFinishing()) {
              //do your action here to prevent the app crashes.
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM