androidx中的lifecycle组件

2020-11-22 23:00:16

参考地址 androidx中的lifecycle组件

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

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

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;/** * @author MengK */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,对应的activity或者fragment实现LifecycleOwner,并调用getLifecycle().addObserverLifecycle().addObserver添加观察者

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LifecycleOwner;

import android.os.Bundle;

/**
 * @author MengK
 */
public class MainActivity extends AppCompatActivity implements LifecycleOwner {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getLifecycle().addObserver(new MyLocationListener(this));
//        MyCommpont myCommpont = new MyCommpont();
//        myCommpont.onCreate();
//        myCommpont.onStart();
//        myCommpont.getLifecycle().addObserver(new MyLocationListener(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

自定义生命周期组件

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

import androidx.annotation.NonNull;import androidx.lifecycle.Lifecycle;import androidx.lifecycle.LifecycleOwner;import androidx.lifecycle.LifecycleRegistry;/** * @author Mengk * @date {2019/9/1} * @description */public class MyCommpont implements LifecycleOwner {

    private LifecycleRegistry lifecycleRegistry;

    public MyCommpont() {
        lifecycleRegistry = new LifecycleRegistry(this);
    }

    public void onCreate() {
        lifecycleRegistry.markState(Lifecycle.State.CREATED);
    }

    public void onStart() {
        lifecycleRegistry.markState(Lifecycle.State.STARTED);
    }

    public void onKillApp() {
        lifecycleRegistry.markState(Lifecycle.State.DESTROYED);
    }


    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return lifecycleRegistry;
    }}

调用

/**
 * @author MengK
 */
public class MainActivity extends AppCompatActivity /*implements LifecycleOwner*/ {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        getLifecycle().addObserver(new MyLocationListener(this));
        MyCommpont myCommpont = new MyCommpont();
        myCommpont.onCreate();
        myCommpont.onStart();
        myCommpont.getLifecycle().addObserver(new MyLocationListener(this));

    }
}




  • 2018-04-02 10:50:59

    mybatis 中的<![CDATA[ ]]>

    在使用mybatis 时我们sql是写在xml 映射文件中,如果写的sql中有一些特殊的字符的话,在解析xml文件的时候会被转义,但我们不希望他被转义,所以我们要使用<![CDATA[ ]]>来解决。

  • 2018-04-03 10:21:35

    jquery实时监听输入框值变化

    在做web开发时候很多时候都需要即时监听输入框值的变化,以便作出即时动作去引导浏览者增强网站的用户体验感。而采用onchange时间又往往是在输入框失去焦点(onblur)时候触发,有时候并不能满足条件。

  • 2018-04-03 10:22:20

    JQuery如何监听DIV内容变化

    这几天在做一个微博的接入,需要判断微博是否被关注,要检查微博标签的DIV是否有“已关注”的字符,但这个DIV的内容是微博JSSDK动态生成。$("#id").html()是获取不到我想要的内容。原因是当我们获取的时候内容还没有改变,所以获取不到,如果就想到监听这个DIV内容变化后,再来获取就个时候就能获取到了。于是产生新的问题,如何监听DIV的变化?

  • 2018-04-04 23:52:03

    PowerManager之PowerManager

    当你在做一些事情时,如果持续时间过长,那么一段时间后屏幕会灭掉,如果你想在你做这些事时屏幕始终保持点亮状态,那么你需要WakeLock的帮助。

  • 2018-04-07 23:35:16

    使用Intent传递对象的两种方式

    Intent 的用法相信你已经比较熟悉了,我们可以借助它来启动活动、发送广播、启动服务等。在进行上述操作的时候,我们还可以在Intent 中添加一些附加数据,以达到传值的效果,比如在FirstActivity 中添加如下代码:

  • 2018-04-10 14:59:59

    JS实现数组去重方法总结(六种方法)

    这篇文章给大家总结下JS实现数组去重方法(六种方法),面试中也经常会遇到这个问题。文中给大家引申的还有合并数组并去重的方法,感兴趣的朋友跟随脚本之家小编一起学习吧