1. Introduction

In order to ensure the security of applications, there are often requirements for security verification such as software verification when switching back from the background to the foreground. In the past, this requirement was actually quite difficult to achieve. But since Google released the Lifecycle component, this requirement has become much simpler. Lifecycle in addition to perceiving the transition from the background back to the foreground, this component makes it easier to implement complex operations that process the Lifecycle. This article is only about how to implement the lifecycle of perception as it cuts back from the background to the foreground.

2. The Lifecycle components

2.1 introduction

Lifecycle components can be used to sense the Lifecycle of activities and fragments.

  • This component is implemented in observer mode. inLife cycle ownerandLife cycle observerTo establish a relationship between observing and being observed. whenLife cycle ownerThe observer is notified when the life cycle of theLife cycle observerAfter receiving the notification, the observer will do various processing.
  • Easily accessibleLife cycle ownerLife cycle of.

Lifecycles Use two main enumerations to track the lifecycles of related components:

  1. Event: LifeCycle events distributed from the framework and LifeCycle classes. These events map to callback events in activities and fragments.
  2. State: The current state of the component that LifeCycle object traces.

2.2 Application Scenarios

  • You can process lifecycle events centrally instead of repeatedly writing lifecycle events (such as unbroadcast) in different activities.
  • It can realize the whole application life cycle.

3. LifeCycle

3.1 Adding to a dependency Library

Add dependencies for LifeCycle to your own project as needed.

    // ViewModel and LiveData
    implementation "android.arch.lifecycle:extensions:$lifecycle_version"
    // alternatively - just ViewModel
    implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" // use -ktx for Kotlin
    // alternatively - just LiveData
    implementation "android.arch.lifecycle:livedata:$lifecycle_version"
    // alternatively - Lifecycles only (no ViewModel or LiveData).
    // Support library depends on this lightweight import
    implementation "android.arch.lifecycle:runtime:$lifecycle_version"
    annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version"
    // alternately - if using Java8, use the following instead of compiler
    implementation "android.arch.lifecycle:common-java8:$lifecycle_version"
    // optional - ReactiveStreams support for LiveData
    implementation "android.arch.lifecycle:reactivestreams:$lifecycle_version"
Copy the code

3.2 LifeCyleOwner

LifeCycleOwner is the observer of the lifecycle. The notification will be handled accordingly. LifeCycleOwner’s interface is simple as follows:

public Lifecycle getLifecycle(a) {
    return mLifecycleRegistry;
}
Copy the code

Add lifecycle observers to activities and Fragments.

lifecycle.addObserver(AppLifecycleObserver(object:AppLifecycleCallback(){
    // Do something
}))
Copy the code

3.3 LifeCycleObserver

LifeCyclObserver is the observed of the lifecycle. Here we need to define what we do in the phases of the life cycle. LifeCycle annotations are needed to indicate in which LifeCycle the method will be invoked. As follows:

class AppLifecycleObserver : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart(a) {
        // Do something
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onStop(a) {
        // Do something
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate(a) {
        // Do something
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause(a) {
        // Do something
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy(a) {
        // Do something
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume(a) {
        // Do something
    }

    // All lifecycles call this method
    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    fun onAny(a) {
        // Do something}}Copy the code

The annotation @onlifecycleevent (Lifecycle.event.on_any) is called, as its name suggests, at all Lifecycle phases.

4. Life cycle awareness before and after application switchover

4.1 Implement the LifeCyCleObserver class

First we implement what happens when we perceive a cut back to the foreground, so the processing we need to implement is written to the LifeCycleObserver. Here we have added callbacks that will be implemented in the Application class.

class AppLifecycleObserver(val callback: AppLifecycleCallback) : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart(a) {
        callback.onStart()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause(a) {
        callback.onPause()
    }
}
Copy the code

And, of course, creating callback classes.

interface AppLifecycleCallback {

    fun onStart(a)

    fun onPause(a)
    
}
Copy the code

4.2 LifeCycleOwner

Next, implement the LifeCycleOwner class in Android. There is also a Flag to be set to record the cutting state of the front and background. Why onResume is foreground operation in onStart instead of onResume? Because when you cut back from the background to the foreground, you call the Activity’s life cycle first, and then call Android. Acitivty OnResume() -> Application OnResume(). If we use onResume in the Application, the Activity gets the onBackground flag. Therefore, if you want to determine the state of cutting back to the foreground in the Activity’s onResume, you need to implement it in the Application state before the onResume state.

  ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleObserver(object :
            AppLifecycleCallback {
            override fun onStart(a) {
                onForeground()
                Log.d(TAG, "onStart")}override fun onPause(a) {
                onBackground()
                Log.d(TAG, "onPause")}}}))fun getAppStatus(a): Boolean {
        return isAppActive
    }

    fun onBackground(a) {
        isAppActive = false
    }

    fun onForeground(a) {
        isAppActive = true
    }
Copy the code

Lifecycle can only be obtained in the Application through ProcessLifecycleOwner.

4.3 Obtaining the Flag from the Acitivty

Although it is possible to implement specific operations that are aware in Android, the practical requirement is that all activities do not need to be aware. In this case, you can obtain the Flag in the Activity and perform related processing according to the Flag.

    override fun onResume(a) {
        super.onResume()

        Log.d("MainActivity"."onResume")

        val app = application as AndroidApplication
        Log.d("MainActivity", app.getAppStatus().toString())
        if (app.getAppStatus()) {
            Log.d("MainActivity"."onResume work")
            Toast.makeText(this."App is in Foreground", Toast.LENGTH_LONG).show()
        }
    }
Copy the code

4.4 Actual Effect

5. To summarize

  • LifeCycleObserverReferences should be avoidedContextandViewAnd so on to prevent memory leaks. You can address this problem with a callback, which is called inLifeCycleObserverAdd callbacks to activities and fragments.
  • althoughLifeCycleIt works, but don’t abuse it. If you don’t need a lot of lifecycle processing in your project, you don’t need to use this component.

Making: github.com/HyejeanMOON…