Getting a Lifecycle

Everything dealing with Lifecycle comes down to a LifecycleOwner. You have several possibilities of where to get one of those.

…From a FragmentActivity or a Support Fragment

If you are using version 26.1.0 or higher of the Support Library artifacts, then FragmentActivity and the android.support.v4.app.Fragment class both implement LifecycleOwner.

If you are using an older version of the Support Library artifacts… you really should upgrade to at least 26.1.0 to use the Architecture Components.

…From an AppCompatActivity

Perhaps you are using the appcompat-v7 artifact. In that case, you are inheriting from AppCompatActivity instead of FragmentActivity or Activity.

However, since AppCompatActivity inherits from FragmentActivity, if you are using 26.1.0 or higher of appcompat-v7, your AppCompatActivity subclasses will also implement LifecycleOwner.

…From an Activity or Fragment

Perhaps you are using the classic Activity and Fragment classes, or from classes that extend those (e.g., WearableActivity). Those will never directly implement LifecycleOwner, as framework classes cannot depend upon libraries.

The simplest solution is to switch to inheriting from FragmentActivity and the corresponding backport of Fragment.

Otherwise, this means that we need to handle this in a more complex fashion, outlined later in the chapter.

…From Anything Else

In principle, you could have other objects that are themselves tied into the activity and fragment lifecycle. After all, the backport of fragments in the Support Library are just that sort of “other objects”. It so happens that Google takes care of managing that backport. However, you might find other objects that, for whatever reason, are similar in concept to the fragments backport and therefore should be suppliers of lifecycle events.

In that case, you can implement LifecycleOwner on those classes. However, you will also need to call handleLifecycleEvent() method on the LifecycleRegistry at appropriate points.

This will be illustrated with support for ordinary activities, shown later in the chapter.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.