
As I mentioned in the previous article, the Lifecycle component is designed to simplify work with the life cycle, and avoid Kalbeks with Activity / Fragment in our component, which should respond to life cycle events. In this article, we will analyze in detail how it works and how to work with it.
The component itself consists of the following classes: Lifecycle, LifecycleActivity, LifecycleFragment, LifecycleService, ProcessLifecycleOwner, LifecycleRegistry. Interfaces: LifecycleOwner, LifecycleObserver, LifecycleRegistryOwner.
')
Lifecycle is a class that stores information about the state of the life cycle and allows other objects to track it using the LifecycleObserver implementation. Consists of methods: addObserver (LifecycleObserver), removeObserver (LifecycleObserver) and getCurrentState (). As is clear from the names for adding a subscriber, deleting and, accordingly, obtaining the current state.
To describe the state there are two enum. The first Events - which denotes the change of the cycle and the second State - which describes the current state.
Events - repeats life cycle stages and consists of ON_CREATE, ON_RESUME, ON_START, ON_PAUSE, ON_STOP, ON_DESTROY, and also ON_ANY which informs about state changes without being tied to a specific stage. Tracking cycle changes are done by marking the method in the observatory with the OnLifecycleEvent annotation, to which an event of interest is passed as a parameter.
@OnLifecycleEvent(Lifecycle.Event.ON_ANY) void stateUpdated() {
State - consists of the following constants: INITIALIZED, CREATED, STARTED, RESUMED, DESTROYED. To get the state, use the getCurrentState () method from the Lifecycle. Also in Enum State, the itAtLeast (State) method has been edited, which answers the question whether the State is higher or equal to the passed as parameter.
To work with the Lifecycle component, we need to determine the owner, that is, the owner of the life cycle and the observer, the one who will be subscribed to it. The owner can have any number of subscribers, it is also worth noting that the observer will be informed about the state change, even before the owner has called super () on the corresponding life-cycle method.
Owner must implement the LifecycleOwner interface, which contains one getLifecycle () method that returns an instance of the Lifecycle holder class.
Observer must implement the LifecycleObserver token interface.
For self-advertisement of the custom Activity / Fragment, as the owner, who do not yet support the new component and therefore do not have the Lifecycle implementation, the LifecycleRegistry class and the LifecycleRegistryOwner interface are created.
The LifecycleRegistryOwner interface , which in turn extends the LifecycleOwner interface with the only difference that the getLifecycle () method returns LifecycleRegistry instead of Lifecycle.
The LifecycleRegistry class , which is an extension of the Lifecycle and takes all the support work, we just need to create an instance of it.
Here is the implementation:
public class MyFragment extends Fragment implements LifecycleRegistryOwner { LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this); @Override public LifecycleRegistry getLifecycle() { return lifecycleRegistry; } }
The android.arch.lifecycle package contains 4 implementations owner: LifecycleActivity, LifecycleFragment, LifecycleService, ProcessLifecycleOwner.
LifecycleActivity is a FragmentActivity with the implementation of LifecycleRegistryOwner. It is a temporary solution to simplify work and as stated in the documentation until Lifecycle is integrated with the support library.
LifecycleFragment is a Fragment from the support.v4 package, which also implements LifecycleRegistryOwner as is the case with LivecycleActivity and is a temporary solution.
LifecycleService is a Service that is also LifecycleOwner.
ProcessLifecycleOwner is the class that represents the lifecycle of the entire process. This class will be useful if you need to track the care of the application in the background or return it to the foreground.
In order to bind owner and observer you need to call getLifecycle (). AddObserver (LifecycleObserver) from the owner. Below I will demonstrate the work of all these classes. For the demonstration, I created the class SomeObserver, which will log ON_CREATE and ON_STOP calls, I will use it for all types of owners, so for simplicity I added enum, a constant from which will be passed to the constructor and then used to distinguish the owner by logs :
public class SomeObserver implements LifecycleObserver { private Owner owner; public SomeObserver(Lifecycle lifecycle, Owner owner) { this.owner = owner; lifecycle.addObserver(this); } @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) void onCreate() { Log.d(«Observer», owner + «: onCreate»); } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void onStop() { Log.d(«Observer», owner + «: onStop»); } enum Owner { ACTIVITY, FRAGMENT, PROCESS, SERVICE } }
In general, the work with all the classes is similar, all we need is to create a copy of the observatory and subscribe it to the Lifecycle, in my implementation we pass our Lifecycle to the designer of the observer, the observer is already engaged in a subscription. This approach is just a matter of taste and no more.
Listing LifecycleActivity:
public class MainActivity extends LifecycleActivity { SomeObserver someObserver = new SomeObserver(getLifecycle(), SomeObserver.Owner.ACTIVITY); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(«Owner», «onCreate»); setContentView(R.layout.activity_main); } @Override protected void onStop() { super.onStop(); Log.d(«Owner», «onStop»); } }
Listing LifecycleFragment:
public class MyFragment extends LifecycleFragment { SomeObserver someObserver = new SomeObserver(getLifecycle(), SomeObserver.Owner.FRAGMENT); public MyFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.<i>fragment_my</i>, container, false); } }
Listing LifecycleService, it works for 5 seconds and ends, I run it from Application:
public class MyService extends LifecycleService { SomeObserver someObserver; @Override public int onStartCommand(Intent intent, int flags, int startId) { someObserver = new SomeObserver(getLifecycle(), SomeObserver.Owner.SERVICE); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { stopSelf(); } }, 5000); return super.onStartCommand(intent, flags, startId); } }
And for ProcessLifecycleOwner, I decided to extend the Application, as you can see ProcessLifecycleOwner is made as a singleton and is a completely separate component:
public class CustomApplication extends Application { private SomeObserver processObserver; @Override public void onCreate() { super.onCreate(); processObserver = new SomeObserver(ProcessLifecycleOwner.get().getLifecycle(), SomeObserver.Owner.PROCESS); Intent intent = new Intent(this, MyService.class); startService(intent); } }
You can see the full listing on the link:
hereAlso useful links:
one and
two .
In the next article, we will analyze the LiveData component in more detail.
Android Architecture Components. Part 1. IntroductionAndroid Architecture Components. Part 2. LifecycleAndroid Architecture Components. Part 3. LiveDataAndroid Architecture Components. Part 4. ViewModel