什么是AAC?

Google官方DEMO
即Android Architecture Components,谷歌在Google I/O 2017上发布的帮助开发者构建易于维护测试/健壮的架构设计方案。它的核心应该是基于观察者模式的,其主要的两大内容就是:

  1. 生命周期相关的 Lifecycle-aware Components(生命周期感知组件)
  2. 数据库解决方案 Room

组件功能:处理数据持久化和管理生命周期(生命周期感知组件执行操作以响应另一个组件(例如活动和片段)的生命周期状态的更改),能够有效的避免内存泄漏等问题。

主要架构图如下:
Android AAC学习(一)

如何使用AAC相关组件:
app.gradlew中添加依赖LiveData以及ViewModel

dependencies {
    implementation 'android.arch.lifecycle:extensions:1.1.1'
    annotationProcessor 'android.arch.lifecycle:compiler:1.1.1'
}

时间有限,本篇主要讲解

Lifecycle管理生命周期

Lifecycle 介绍:

Lifecycle 组件指的是 android.arch.lifecycle 包下提供的各种类与接口,可以让开发者构建能感知其他组件(主要指Activity 、Fragment)生命周期(lifecycle-aware)的类。

基本的使用流程:

  1. 让需要监听Activity/Fragment的类实现LifecycleObserver接口
  2. 在相关生命周期方法中做出的动作封装成方法并且加上对应生命周期的注解,形成映射
  3. 被监听的Activity/Fragment实现LifecycleOwner接口,实例化监听类,最后注册监听

监听类: 其中各个注解对应的就是被监听Ac/Fg的生命周期方法

package com.wdl.aac;

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.OnLifecycleEvent;

/**
 * 创建时间: 2019/3/22 11:35
 * 描述:    Activity生命周期的管理类,与实现了LifecycleOwner接口的Ac/Fg等建立映射关系。有效避免内存泄漏
 *          对外界提供一个接口,管理生命周期使得生命周期从Activity/Fg解耦出来
 */
@SuppressWarnings("unused")
public class ActivityLifeObserver implements LifecycleObserver {

    private static final String TAG = ActivityLifeObserver.class.getSimpleName();

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCreate() {
        LogUtil.e("onCreate");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStart() {
        LogUtil.e("onStart");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        LogUtil.e("onResume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        LogUtil.e("onPause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        LogUtil.e("onDestroy");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    public void onAny() {
        //LogUtil.e("onAny");
    }
}

Ac/Fg: 被监听对象,先实例化LifecycleRegistry后注册监听即可

package com.wdl.aac;

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.LifecycleRegistry;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.wdl.aac.data.User;

@SuppressWarnings("unused")
public class MainActivity extends AppCompatActivity implements LifecycleOwner {
    private ActivityLifeObserver observer;
    private LifecycleRegistry registry;
    private UserViewModel userViewModel;
    private TextView mTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 实例化LifecycleRegistry
        registry = new LifecycleRegistry(this);
        // 实例化要监听的生命周期的类
        observer = new ActivityLifeObserver();
        // 注册监听
        registry.addObserver(observer);
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
        mTv = findViewById(R.id.tv_content);
        mTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userViewModel.getUserInfo().setValue(new User(1,"wdl",23,"Fuzhou"));
            }
        });

        //userViewModel.getUserInfo().setValue();
        final Observer<User> userObserver = new Observer<User>() {
            @Override
            public void onChanged(@Nullable User user) {
                assert user != null;
                mTv.setText(user.toString());
            }
        };
        userViewModel.getUserInfo().observe(this,userObserver);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 移除监听
        registry.removeObserver(observer);
    }

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

LiveData && ViewModel

  • LiveData:构建数据对象,以便在基础数据库更改时通知视图。LiveData 是一种持有可被观察数据的类(an observable data holder class)。和其他可被观察的类不同的是,LiveData是有生命周期感知能力的(lifecycle-aware,),这意味着它可以在 activities, fragments, 或者 services 生命周期是活跃状态时更新这些组件。

  • ViewModel:存储应用程序轮换中未销毁的UI相关数据。内部持有LiveData,管理LiveData。

两者的关系结构:
Android AAC学习(一)

通常使用的是LiveData的实现类MutableLiveData,其中LiveData常用的方法有:
设置数据的两种方式: 其中setValue用于主线程,postValue用于子线程中

 @Override
    public void postValue(T value) {
        super.postValue(value);
    }

    @Override
    public void setValue(T value) {
        super.setValue(value);
    }

其中最重要的方法为:

观测LiveData设置的数据变化,基于观察者设计模式,和生命周期进行绑定。

 /**
     * Adds the given observer to the observers list within the lifespan of the given
     * owner. The events are dispatched on the main thread. If LiveData already has data
     * set, it will be delivered to the observer.
     * <p>
     * The observer will only receive events if the owner is in {@link Lifecycle.State#STARTED}
     * or {@link Lifecycle.State#RESUMED} state (active).
     * <p>
     * If the owner moves to the {@link Lifecycle.State#DESTROYED} state, the observer will
     * automatically be removed.
     * <p>
     * When data changes while the {@code owner} is not active, it will not receive any updates.
     * If it becomes active again, it will receive the last available data automatically.
     * <p>
     * LiveData keeps a strong reference to the observer and the owner as long as the
     * given LifecycleOwner is not destroyed. When it is destroyed, LiveData removes references to
     * the observer &amp; the owner.
     * <p>
     * If the given owner is already in {@link Lifecycle.State#DESTROYED} state, LiveData
     * ignores the call.
     * <p>
     * If the given owner, observer tuple is already in the list, the call is ignored.
     * If the observer is already in the list with another owner, LiveData throws an
     * {@link IllegalArgumentException}.
     *
     * @param owner    The LifecycleOwner which controls the observer
     * @param observer The observer that will receive the events
     */
    @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
        if (existing != null && !existing.isAttachedTo(owner)) {
            throw new IllegalArgumentException("Cannot add the same observer"
                    + " with different lifecycles");
        }
        if (existing != null) {
            return;
        }
        owner.getLifecycle().addObserver(wrapper);
    }

使用相关:

  1. 新建UserViewModel继承自ViewModel
  2. 内部创建一个MutableLiveData<>实例
  3. Activity等中获取ViewModel实例
  4. 创建监听
  5. 绑定监听

步骤1,2:

package com.wdl.aac;

import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;

import com.wdl.aac.data.User;

/**
 * 创建时间: 2019/3/22 13:51
 * 描述:    TODO
 */
@SuppressWarnings("unused")
public class UserViewModel extends ViewModel {
    private MutableLiveData<User> userInfo;

    public MutableLiveData<User> getUserInfo() {
        if (userInfo == null) {
            userInfo = new MutableLiveData<>();
        }
        userInfo.setValue(load());
        return userInfo;
    }

    public void setInfo(User user) {
        if (userInfo != null)
            userInfo.setValue(user);
    }

    private User load() {
        return new User(1, "1", 1, "1");
    }
}

创建实例,监听以及绑定: 注意Activity/Fg中是否注册LifecycleOwner

		 // 获取实例
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
         //userViewModel.getUserInfo().setValue();
        // 创建一个监听
        final Observer<User> userObserver = new Observer<User>() {
            /**
             * 监听回调(数据源更改)
             * @param user User
             */
            @Override
            public void onChanged(@Nullable User user) {
                assert user != null;
                mTv.setText(user.toString());
            }
        };
        // 进行绑定
        userViewModel.getUserInfo().observe(this,userObserver);

使用起来特别的方便。。。。

参考自:
https://juejin.im/post/5b30e39bf265da599423510a#heading-19
https://blog.csdn.net/yoonerloop/article/details/80869994

Demo上传至Github

相关文章:

  • 2021-09-17
  • 2021-12-06
  • 2021-11-09
  • 2021-08-10
  • 2021-11-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-24
  • 2021-11-17
  • 2021-07-16
  • 2021-07-16
  • 2022-03-07
  • 2021-08-15
相关资源
相似解决方案