简体   繁体   中英

Activity lifecycle observer - how to know when an activity instance is destroyed?

Imagine I have a class MyLibrary , that requires to be passed an Activity as a parameter to it's constructor: public MyLibrary(Activity someActivity) . Is there a way to attach an observer to someActivity within the MyLibrary constructor, so that MyLibrary would know when someActivity gets destroyed?

I'm using Bumptech's Glide for async image loading and in several places in their issues it is mentioned that after passing a context, activity or fragment to it's Glide.with() function, Glide will automatically pause images that are currently loading if the passed object gets destroyed. ( Example ) I'm wondering how Glide figures out when to stop loading once the given context, activity or fragment is destroyed, how does it observe it?

Ideally I'd like to do something along the following lines (note this is a made up example):

public MyLibrary(Activity someActivity){
    someActivity.addLifecycleObserver(new LifecycleObserver(){
        @Override
        public void onStart() {}

        @Override
        public void onStop() {}

        @Override
        public void onDestroy() {}
    });
}

Google just released an architectural library which handles your use case. Check out the guide

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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