Hello I’m LifeCycle from the bottom of the Jetpack eco-chain.

My role is to sense the Activity/Fragment life cycle and perform the tasks you assign me in the appropriate life cycle. I adhere to the Slogan, Less Code, Less bug of Jetpack! Use me, pack you offline without collapse, online without Bug, every day on time off work, embark on the peak of life, win bai Fu Mei, automatically omit 300 words……

That’s a little off topic. Drag it back.

Although I mock myself as coming from the bottom of the Jetpack ecosystem, I’m actually the most integral part of the Jetpack family. The left look at LiveData, the right look at ViewModel, they show a pair of disdain, “without you in the day, we are not the same live well!”

I first appeared in version 26.1.0 of the Support library. How did you perceive the declaration cycle before that? Just then, a programmer with a still bushy hair tossed his heirloom code out of the darkness.

public class LocationUtil {

    public void startLocation(a) {... }public void stopLocation(a) {... }}Copy the code

And then what? You have to use it like this.

public class LocationActivity extends AppCompatActivity {

    private LocationUtil locationUtil = new LocationUtil();

    @Override
   public void  onResume(a){ locationUtil.startLocation(); . }@Override
   public void onPause(a){ locationUtil.stopLocation(); . }}Copy the code

“My LocationUtil is proven to solve life cycle problems perfectly and never leaks!” the programmer bragged.

I can not help but sniff, you are single for a long time a person lu code lu habit! Yeah, it’s good for you to use it alone. But for a modern, large project, say you have 20 pages that need to use your LocationUtil, and those 20 pages are assigned to five programmers. Can you make sure that all the lifecycle code is added as you expected? Or maybe you’ve already left your job, didn’t leave a thorough document, and you’ll be greeted by a new employee because of an inexplicable memory leak.

In another extreme case, the damn product manager lets you turn on and off positioning in onCreate() and onDestroy () instead of onResume() and onPause(), respectively. At this moment, do you feel like pulling out a 40-meter knife?

The way you write it, you mumble a bunch of code, and you’re so fragile!

He blushed and could only weakly explain, “You can go on, show me your code!”

I was prepared. The code. Let LocationUtil implement the LifeCycleObserver interface first.

class LocationUtil( ) : LifeCycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun startLocation( ){ ...... } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun stopLocation( ){ ...... }}Copy the code

Then for any lifecycle component that implements the LifecycleOwner interface and needs to use LocationUtil, just add the following line of code.

lifecycle.addObserver(LocationUtil( ))
Copy the code

I made it possible for third-party components such as LocationUtil to access the lifecycle internally, so that the lifecycle logic that would otherwise be done in the lifecycle component Activity/Fragment can be done directly inside the component, further decoupling. Even with the perverted product manager requirements mentioned above, you only need to change the internal implementation of LocationUtil, not the external one. See, a lot of times when you think other people’s needs are unreasonable, it’s actually your own problem.

There’s no sound. I think I’m all over it. That’s just my basic usage, but here are some more advanced ones. Don’t blink.

Listen for background switching before and after application

Some banking apps have such a function. When switching to the background, users will be prompted, “XX mobile banking is running in the background, please pay attention to your safety!” . With me LifeCycle, it’s incredibly simple.

class KtxAppLifeObserver : LifecycleObserver {@onlifecycleEvent (Lifecycle.event.on_start) fun onForeground() {txt.app.toast (" application into foreground ")} @onlifecycleEvent (Lifecycle.event.on_stop) fun onBackground() {txt.app.toast (" app into the background ")}}Copy the code

Then when the Application starts, such as ContentProvier, Application, call the following code:

 ProcessLifecycleOwner.get().lifecycle.addObserver(KtxAppLifeObserver())
Copy the code

As you can see from the code, this is implemented by my family member ProcessLifecycleOwner. It can sense the entire lifecycle of an application process, making it easy to listen in on switching between applications.

Global Management Activity

I’m sure you’ve all done this before. In certain cases, you need to finish all activities that you’ve started, or you need to close a specific Activity. It is common practice to save activities that have been turned on or off in the BaseActivity lifecycle callback. While the implementation is elegant, how do you reduce the burden of an increasingly bloated BaseActivity? It’s time again for me to LifeCycle.

class KtxLifeCycleCallBack : Application.ActivityLifecycleCallbacks {

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        KtxManager.pushActivity(activity)
        "onActivityCreated : ${activity.localClassName}".loge()
    }

    override fun onActivityStarted(activity: Activity) {
        "onActivityStarted : ${activity.localClassName}".loge()
    }

    override fun onActivityResumed(activity: Activity) {
        "onActivityResumed : ${activity.localClassName}".loge()
    }

    override fun onActivityPaused(activity: Activity) {
        "onActivityPaused : ${activity.localClassName}".loge()
    }

    override fun onActivityDestroyed(activity: Activity) {
        "onActivityDestroyed : ${activity.localClassName}".loge()shejiyuanze
        KtxManager.popActivity(activity)
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) {
    }

    override fun onActivityStopped(activity: Activity) {
        "onActivityStopped : ${activity.localClassName}".loge()
    }
}
Copy the code

Through my other family members, Application. ActivityLifecycleCallbacks, you can listen to all the Activity of all life cycle. Just register the Callback in the Application.

application.registerActivityLifecycleCallbacks(KtxLifeCycleCallBack())
Copy the code

According to the single responsibility principle, a class does one thing. This approach centralizes the Activity management responsibilities into a single class, reducing code coupling. There are two problems with the original method. First, you must inherit BaseActivity to manage the current Activity. Again, this is about collaborative development, not wanting to inherit, or forgetting to inherit. Second, putting too much responsibility on BaseActivity doesn’t follow basic design principles.

A Handler that automatically handles the lifecycle

An idea from a program, not an ape. Remove Handler messages in the onDestroy method without additional manual processing to avoid memory leaks.

public class LifecycleHandler extends Handler implements LifecycleObserver {

    private LifecycleOwner lifecycleOwner;

    public LifecycleHandler(final LifecycleOwner lifecycleOwner) {
        this.lifecycleOwner = lifecycleOwner;
        addObserver();
    }

    public LifecycleHandler(final Callback callback, final LifecycleOwner lifecycleOwner) {
        super(callback);
        this.lifecycleOwner = lifecycleOwner;
        addObserver();
    }

    public LifecycleHandler(final Looper looper, final LifecycleOwner lifecycleOwner) {
        super(looper);
        this.lifecycleOwner = lifecycleOwner;
        addObserver();
    }

    public LifecycleHandler(final Looper looper, final Callback callback, final LifecycleOwner lifecycleOwner) {
        super(looper, callback);
        this.lifecycleOwner = lifecycleOwner;
        addObserver();
    }

    private void addObserver(a) {
        notNull(lifecycleOwner);
        lifecycleOwner.getLifecycle().addObserver(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void onDestroy(a) {
        removeCallbacksAndMessages(null);
        lifecycleOwner.getLifecycle().removeObserver(this); }}Copy the code

A smarter event bus

The evolution of the Android message Bus: Replacing RxBus and EventBus with LiveDataBus is an article by Meituan Technical team. In fact, neither EventBus nor RxBus has lifecycle awareness, which is shown in the code to call the de-registration method. LiveDataBus is implemented based on LiveData, which in turn gains LifeCycle awareness without manual de-registration and without the risk of memory leaks.

LiveEventBus
	.get("key_name", String.class)
	.observe(this.new Observer<String>() {
	    @Override
	    public void onChanged(@Nullable String s) {}});Copy the code

Subscribe anytime, automatically unsubscribe, simple as that.

Use with coroutines

Coroutines are new to Android asynchronous processing and not only LifeCycle, ViewModel, LIveData and other Jetpack components provide specific support for them.

To use LifeCycle coroutines support, you need to add androidx. LifeCycle: LifeCycle – runtime – KTX: 2.2.0 – alpha01 or later. The support library defines a LifecycleScope for each LifeCycle object. Coroutines started within this scope will be cancelled automatically when LifeCycle is destroyed. You can use the lifecycle. CoroutineScope or lifecycleOwner. Visit lifecycle coroutineScope lifecycleScope attribute. Here is a simple example:

class MyFragment: Fragment() {
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            viewLifecycleOwner.lifecycleScope.launch {
                val params = TextViewCompat.getTextMetricsParams(textView)
                val precomputedText = withContext(Dispatchers.Default) {
                    PrecomputedTextCompat.create(longTextContent, params)
                }
                TextViewCompat.setPrecomputedText(textView, precomputedText)
            }
        }
    }
Copy the code

Use Kotlin coroutines with architectural components.

The last

With LifeCycle, what can you do?

Write less code, make fewer mistakes.

Life cycle processing tends to be standardized, which is what Jetpack is trying to bring to us, making development more standardized with fewer errors, fewer crashes and fewer memory leaks. Take a look at your project and if there are places where LifeCycle is not used to solve LifeCycle problems, replace them!

Finally, I recommend my Jetpack MVVM open source project, WanAndroid, for more bugs you will find.

The reader who has patience to see this must ridicule, not hardcore at all! This also can’t blame me, use a piece, how hardcore.

Stay tuned for Jetpack’s core LifeCycle tutorial!

This article first published wechat official account: BingxinshuaiTM, focusing on Java, Android original knowledge sharing, LeetCode problem solving.

More latest original articles, scan code to pay attention to me!