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

4.2k views Asked by At

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() {}
    });
}
1

There are 1 answers

0
easycheese On BEST ANSWER

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