IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Jetpack--Lifecycle使用和源码解析 -> 正文阅读

[移动开发]Jetpack--Lifecycle使用和源码解析

Lifecycle 是什么?
Google官方解释Lifecycle:
生命周期感知型组件可执行操作来响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。
说白了就是可以监听Activity/Fragment的生命周期。

古老的生命周期监听做法:

class MainActivity : AppCompatActivity() {
    private var mainActivityLifeListener : MainActivityLifeListener ?= null
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    mainActivityLifeListener = MainActivityLifeListener();
}

override fun onResume() {
    super.onResume()
    mainActivityLifeListener?.onResume()
}

override fun onDestroy() {
    super.onDestroy()
    mainActivityLifeListener?.onDestroy()
}

}



class MainActivityLifeListener {
    private val TAG = "MainActivityLifeListener"

    fun onResume() = Log.d(TAG,"onResume ...");

    fun onDestroy() = Log.d(TAG,"onDestroy ...");
}

上面的实例代码实现监听MainActivity的生命周期,但是存在以下问题:

1.若需要监听的Activity/Fragment 比较多,就需要多次重复的调用MainActivityLifeListener.kt中的方法,而且容易出现遗漏

2.被监听的Activity/Fragment 代码冗余

采用Lifecycle监听生命周期

方法一:继承LifecycleObserver的自定义监听器实现

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    //继承LifecycleObserver的自定义监听器实现
    lifecycle.addObserver(Myoberver())
    }
}
class Myoberver:LifecycleObserver {

    private val TAG = "Myoberver"

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun connect() = Log.d(TAG,"vivivd Onresume")

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun disconnect() = Log.d(TAG,"vivivd Ondestroy")

}

方法二:内部类继承LifecycleObserver

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    //内部类 实现监听
    lifecycle.addObserver(Myoberver())
}

inner class Myoberver:LifecycleObserver{
    private val TAG = "Myoberver"

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun connect() = Log.d(TAG,"vivivd Onresume")

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun disconnect() = Log.d(TAG,"vivivd Ondestroy")
    }
}

方法三:采用接口继承LifecycleObserver

interface IPresenter :LifecycleObserver{

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun connect()

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun disconnect()
}
class MyObserver :IPresenter {
    private val TAG ="MyObserver"
    override fun connect() {
        Log.d(TAG, "connect: vivid ")
    }

    override fun disconnect() {
        Log.d(TAG, "disconnect: vivid ")
    }
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    //使用接口继承LifecycleObserver 实现接口从而实现监听
    lifecycle.addObserver(MyObserver())
    }

}

通过实例代码可以看出Lifecycle采用了观察者设计模式,简单来说就是MyObserver长了眼睛一直盯着MainActivity,只要MainActivity的生命周期发生变化MyObserver就可以感知到。

但是MyObserver是怎么感知MainActivity的生命周期?

不管采用上述那种方式,最终都要执行:

lifecycle.addObserver(MyObserver())

问题1:lifecycle是怎么来的?

问题2:addObserver做了什么?

问题3:怎么实现监听MainActivity生命周期?

MainActivity-->AppCompatActivity-->FragmentActivity-->ComponentActivity

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
    ContextAware,
    LifecycleOwner,
    ViewModelStoreOwner,
    HasDefaultViewModelProviderFactory,
    SavedStateRegistryOwner,
    OnBackPressedDispatcherOwner,
    ActivityResultRegistryOwner,
    ActivityResultCaller {
    ....
}

public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
    @NonNull
    Lifecycle getLifecycle();
}

问题1答:

可以看出MainActivity继承了ComponentActivity,而ComponentActivity实现了LifecycleOwner 接口

所以lifecycle是从LifecycleOwner接口中的getLifecycle方法获取。

问题2答:

addObserver(MyObserver())执行(两眼一闭,只关心observer的去向)

LifecycleRegistry.java实现如下:

@Override
public void addObserver(@NonNull LifecycleObserver observer) {
enforceMainThreadIfNeeded("addObserver");
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
......
}
static class ObserverWithState {
    State mState;
    LifecycleEventObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {
    mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
    mState = initialState;
}
//注意:上面参数都是Observer 这里往后都转成了Object
@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
......

    return new ReflectiveGenericLifecycleObserver(object);

}
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;

    ReflectiveGenericLifecycleObserver(Object wrapped) {
    mWrapped = wrapped;
    mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }
......
}

最后mInfo 拿到了我们传进来的MyObserver的字节码内容。至此无法继续往下查看

所以addObserver执行会让ReflectiveGenericLifecycleObserver.java文件中的mInfo拿到我们实际的字节码文件。

问题3答:

重新打开ComponentActivity.java中的onCreate()

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    // Restore the Saved State first so that it is available to
    // OnContextAvailableListener instances
    mSavedStateRegistryController.performRestore(savedInstanceState);
    mContextAwareHelper.dispatchOnContextAvailable(this);
    super.onCreate(savedInstanceState);
    ReportFragment.injectIfNeededIn(this);//借鉴Glide实现原理
    if (mContentLayoutId != 0) {
        setContentView(mContentLayoutId);
    }
}
public static void injectIfNeededIn(Activity activity) {
    if (Build.VERSION.SDK_INT >= 29) {
        // On API 29+, we can register for the correct Lifecycle callbacks directly
        LifecycleCallbacks.registerIn(activity);
    }
// Prior to API 29 and to maintain compatibility with older versions of
// ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
// need to support activities that don't extend from FragmentActivity from support lib),
// use a framework fragment to get the correct timing of Lifecycle events
    android.app.FragmentManager manager = activity.getFragmentManager();
    if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
        manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
        // Hopefully, we are the first to make a transaction.
        manager.executePendingTransactions();
    }
}

其实就是在MainActivity上面覆盖了一层空白的ReportFragment,二者进行了绑定,所以可以感知到MainActivity的生命周期。

ReportFragment和MainActivity绑定了,那到底是怎么实现MainActivity生命周期监听的?

既然二者已经绑定了,那么MainActivity进入了onResume,同样ReportFragment也会进入onResume

@Override
public void onResume() {
    super.onResume();
    dispatchResume(mProcessListener);
    dispatch(Lifecycle.Event.ON_RESUME);
}

上面通过dispatch分发了Lidecycle的ON_RESUME事件。

private void dispatch(@NonNull Lifecycle.Event event) {
    if (Build.VERSION.SDK_INT < 29) {
        // Only dispatch events from ReportFragment on API levels prior
        // to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
        // added in ReportFragment.injectIfNeededIn
        dispatch(getActivity(), event);
    }
}
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
    //SDK > 29
    if (activity instanceof LifecycleRegistryOwner) {
        ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
        return;
    }

//SDK < 29 
//activity 就是MainActivity,上面追了MainActivity实现了LifecycleOwner
if (activity instanceof LifecycleOwner) {
    Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
        }
    }
}
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    enforceMainThreadIfNeeded("handleLifecycleEvent");
    moveToState(event.getTargetState()); //这里是关键点
    //moveToState的参数是根据event事件转化为对应的State
    //也就是说moveToState移动的是状态
}

private void moveToState(State next) {
    if (mState == next) {
        return;
    }
mState = next;
if (mHandlingEvent || mAddingObserverCounter != 0) {
    mNewEventOccurred = true;
    // we will figure out what to do on upper level.
    return;
}
    mHandlingEvent = true;
    sync();
    mHandlingEvent = false;
}

?handleLifecycleEvent中执行moveToState但参数是通过Lifecycle.Event事件转化而来,

具体如下:

@NonNull
public State getTargetState() {
    switch (this) {
        case ON_CREATE:
        case ON_STOP:
            return State.CREATED;
        case ON_START:
        case ON_PAUSE:
            return State.STARTED;
        case ON_RESUME:
            return State.RESUMED;
        case ON_DESTROY:
            return State.DESTROYED;
        case ON_ANY:
            break;
    }
    throw new IllegalArgumentException(this + " has no target state");
}

接下来看一下具体State有那些状态

public enum State{
    DESTROTED,
    INIRIALIZED,
    CREATED,
    STARTED,
    RESUMED;
......

}

这里一共6种生命周期5种状态,先由Lifecycle.Event事件推动状态,后由状态调整对应的Lifecycle.Event?

private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
        + "garbage collected. It is too late to change lifecycle state.");
    }
while (!isSynced()) {
    mNewEventOccurred = false;
    // no need to check eldest for nullability, because isSynced does it for us.
    if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
        backwardPass(lifecycleOwner); //关键步骤
    }
    Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
    if (!mNewEventOccurred && newest != null
    && mState.compareTo(newest.getValue().mState) > 0) {
        forwardPass(lifecycleOwner);//关键步骤
    }
    }
    mNewEventOccurred = false;
}

?可以看出是通过被观察者的状态和观察者当前的状态的枚举大小来判断是执行backwardPass/forwardPass方法。

private void forwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
    mObserverMap.iteratorWithAdditions();
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
        ObserverWithState observer = entry.getValue();
    while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
        && mObserverMap.contains(entry.getKey()))) {
    pushParentState(observer.mState);
    final Event event = Event.upFrom(observer.mState);//通过状态获取对应的事件
    if (event == null) {
        throw new IllegalStateException("no event up from " + observer.mState);
    }
        observer.dispatchEvent(lifecycleOwner, event);//回调执行事件
        popParentState();
       }
    }
}
//LifecycleRegistry.java
void dispatchEvent(LifecycleOwner owner, Event event) {
    State newState = event.getTargetState();
    mState = min(mState, newState);
    mLifecycleObserver.onStateChanged(owner, event);
    mState = newState;
}

?onStateChanged最终回到了问题2中的ReflectiveGenericLifecycleObserver.java文件

class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;

    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
        mInfo.invokeCallbacks(source, event, mWrapped);
    }
}

由于mInfo已经获取到了MyObserver.kt的字节码,所以通过反射执行对应的event事件的注解,从而执行对应的MyObserver.kt中的方法,这就是为什么MainActivity.kt中执行onResume(),MyObserver.kt可以感知到对应的onResume()。

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-04-22 18:47:44  更:2022-04-22 18:49:37 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 23:08:26-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码