美文网首页
androidx中的lifecycle组件

androidx中的lifecycle组件

作者: 因为我的心 | 来源:发表于2022-12-19 13:32 被阅读0次

    一、前言:

    Lifecycle-aware components生命周期感知组件执行操作,以响应另一个组件生命周期状态的更改,例如Activity和Fragment。这些组件可以帮助您生成更有组织、更容易维护的轻量级代码。

    注意:LifecycleObserver -过时了,新版本必须引入包。

    // DefaultLifecycleObserver - 引入新包
    implementation "android.arch.lifecycle:common-java8:1.1.1"
    

    1、没有生命周期感知组件,你的代码可能是这样的

    class MyLocationListener {
        public MyLocationListener(Context context, Callback callback) {
            // ...
        }
    
        void start() {
            // connect to system location service
        }
    
        void stop() {
            // disconnect from system location service
        }
    }
    
    class MyActivity extends AppCompatActivity {
        private MyLocationListener myLocationListener;
    
        @Override
        public void onCreate(...) {
            myLocationListener = new MyLocationListener(this, (location) -> {
                // update UI
            });
        }
    
        @Override
        public void onStart() {
            super.onStart();
            myLocationListener.start();
            // manage other components that need to respond
            // to the activity lifecycle
        }
    
        @Override
        public void onStop() {
            super.onStop();
            myLocationListener.stop();
            // manage other components that need to respond
            // to the activity lifecycle
        }
    }
    

    Android框架中定义的大多数应用程序组件都具有附加的生命周期。生命周期由运行在流程中的操作系统或框架代码管理。它们是Android工作原理的核心,您的应用程序必须尊重它们。
    不这样做可能会引发内存泄漏,甚至应用程序崩溃。

    二、lifecycle使用

    1、让需要感知生命周期的组件实现LifecycleObserver接口(老的版本,有过时方法)

    import androidx.lifecycle.Lifecycle;
    import androidx.lifecycle.LifecycleObserver;
    import androidx.lifecycle.OnLifecycleEvent;
     //老的版本
    public class MyLocationListener implements LifecycleObserver {
    
        private Context context;
    
        public MyLocationListener(Context context) {
            this.context = context;
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        void onCreate() {
            showLog("onCreate");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        void onDestroy() {
            showLog("onDestroy");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        void onStart() {
            showLog("onStart");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        void onStop() {
            showLog("onStop");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        void onResume() {
            showLog("onResume");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        void onPause() {
            showLog("onPause");
        }
    
        private void showLog(String msg) {
            Log.e("===MyLocationListener", msg);
        }
    }
    
    //2、新版本
    /**
     * 自定义View 监听Activity 或者Fragment的生命周期
     *  LifecycleObserver -过时了
     *  DefaultLifecycleObserver - 需要导入新包  implementation "android.arch.lifecycle:common-java8:1.1.1"
     */
    class MyLocationListener2(context: Context) : DefaultLifecycleObserver {
        private val context: Context
    
        init {
            this.context = context
        }
        @SuppressLint("LongLogTag")
        override fun onCreate(owner: LifecycleOwner) {
            showLog("onCreate")
        }
        @SuppressLint("LongLogTag")
        override fun onStart(owner: LifecycleOwner) {
            showLog("onStart")
        }
        
        @SuppressLint("LongLogTag")
        override fun onStop(owner: LifecycleOwner) {
            showLog("onStop")
        }
    
        @SuppressLint("LongLogTag")
        override fun onResume(owner: LifecycleOwner) {
            showLog("onResume")
        }
    
        @SuppressLint("LongLogTag")
        override fun onPause(owner: LifecycleOwner) {
            showLog("onPause")
        }
        
        @SuppressLint("LongLogTag")
        override fun onDestroy(owner: LifecycleOwner) {
            showLog("onDestroy")
        }
        private fun showLog(msg: String) {
            Log.e("===MyLocationListener", msg)
        }
    }
    

    对应的activity或者fragment实现LifecycleOwner,并调用getLifecycle().addObserverLifecycle().addObserver添加观察者

    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            var  btnNext = findViewById<Button>(R.id.btn_next)
            btnNext.setOnClickListener {
                //老的版本调用
               getLifecycle().addObserver( MyLocationListener(this))
                //新的版本调用
                getLifecycle().addObserver( MyLocationListener2(this))
            }
        }
     }
    

    打印结果

    2019-09-01 14:53:13.956 22701-22701/com.mengk.lifecyclerdemo E/===MyLocationListener: onCreate
    2019-09-01 14:53:13.960 22701-22701/com.mengk.lifecyclerdemo E/===MyLocationListener: onStart
    2019-09-01 14:53:13.968 22701-22701/com.mengk.lifecyclerdemo E/===MyLocationListener: onResume
    2019-09-01 14:53:16.678 22701-22701/com.mengk.lifecyclerdemo E/===MyLocationListener: onPause
    2019-09-01 14:53:17.282 22701-22701/com.mengk.lifecyclerdemo E/===MyLocationListener: onStop
    2019-09-01 14:53:19.258 22701-22701/com.mengk.lifecyclerdemo E/===MyLocationListener: onDestroy
    

    2、自定义生命周期组件

    如果你有一个自定义类,你想让它成为LifecycleOwner,你可以使用LifecycleRegistry类,但是你需要将事件转发到该类中,如下面的代码示例所示:

    package com.example.myapplication.utils
    import androidx.lifecycle.Lifecycle
    import androidx.lifecycle.LifecycleOwner
    import androidx.lifecycle.LifecycleRegistry
    
    class MyCommpont : LifecycleOwner {
        private val lifecycleRegistry: LifecycleRegistry
    
        init {
            lifecycleRegistry = LifecycleRegistry(this)
        }
    
        fun onCreate() {
            //过时方法
            //lifecycleRegistry.markState(Lifecycle.State.CREATED)
            lifecycleRegistry.setCurrentState(Lifecycle.State.CREATED)
        }
    
        fun onStart() {
            lifecycleRegistry.setCurrentState(Lifecycle.State.STARTED)
        }
    
        fun onResume() {
            lifecycleRegistry.setCurrentState(Lifecycle.State.RESUMED)
        }
    
        fun onKillApp() {
            lifecycleRegistry.setCurrentState(Lifecycle.State.DESTROYED)
        }
    
        override fun getLifecycle(): Lifecycle {
            return lifecycleRegistry
        }
    }
    

    调用

    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            var  btnNext = findViewById<Button>(R.id.btn_next)
            btnNext.setOnClickListener {
                val myCommpont = MyCommpont()
                myCommpont.onCreate()
                myCommpont.onStart()
                myCommpont.lifecycle.addObserver(MyLocationListener2(this))
            }
        }
      }
    

    参考:https://zhuanlan.zhihu.com/p/80681329

    相关文章

      网友评论

          本文标题:androidx中的lifecycle组件

          本文链接:https://www.haomeiwen.com/subject/jduyqdtx.html