Android Lifecycle 生命周期管理

在activity和fragment中可以使用lifecycle对象来监听生命周期。

在Activity中添加监听

class LifecycleCallback : LifecycleObserver {
    //和activity的生命周期一样,create、start、resume、pause、stop、destroy

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun create(owner: LifecycleOwner) {
        log("create")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun start(owner: LifecycleOwner) {
        log("start")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun resume(owner: LifecycleOwner) {
        log("resume")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun pause(owner: LifecycleOwner) {
        log("pause")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stop(owner: LifecycleOwner) {
        log("stop")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun destroy(owner: LifecycleOwner) {
        log("destroy")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    fun event(owner: LifecycleOwner, event: Lifecycle.Event) {
        //包括上面所有的事件,使用event枚举对象区分
        log("event:$event")
    }
}
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //添加观察者监听生命周期的变化
        lifecycle.addObserver(LifecycleCallback())

    }
}

打印日志

//打开activity
create
event:ON_CREATE
start
event:ON_START
resume
event:ON_RESUME


//按home键
pause
event:ON_PAUSE
stop
event:ON_STOP


//从任务管理切换回app
start
event:ON_START
resume
event:ON_RESUME


//按返回键关闭activity
pause
event:ON_PAUSE
stop
event:ON_STOP
destroy
event:ON_DESTROY

 

在Fragment中添加监听

class MainActivity : AppCompatActivity() {

    private val fragment = MainFragment()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        supportFragmentManager.beginTransaction()
                .add(R.id.container, fragment)
                .commit()

    }
}
class MainFragment: Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycle.addObserver(LifecycleCallback())

    }

}

打印日志

//打开activity
create
event:ON_CREATE
start
event:ON_START
resume
event:ON_RESUME


//按home键
pause
event:ON_PAUSE
stop
event:ON_STOP


//从任务管理切换回app
start
event:ON_START
resume
event:ON_RESUME


//按返回键关闭activity
pause
event:ON_PAUSE
stop
event:ON_STOP
destroy
event:ON_DESTROY

 

你可能感兴趣的:(android,kotlin)