当前位置:网站首页>How does activity implement lifecycleowner?
How does activity implement lifecycleowner?
2022-06-23 14:14:00 【User 9239674】
We all know Activity Can be used as LifecycleOwner by LiveData Provide conditions for the use of , that Activity How to achieve LifecycleOwner What about ?
Activity Although it did LifecycleOwner Interface , But it doesn't implement the relevant processing , But by adding a Fragment To represent Lifecycle Distribution of . Such passage Fragment agent Activity Behavior design is also common in other libraries , Relatively more uninhibited and elegant .
SupportActivity
Activity By inheritance SupportActivity Realization LifecycleOwner Interface . Pay attention to AndroidX in SupportActivity Renamed as ComponentActivity
public class SupportActivity extends Activity implements LifecycleOwner {
...
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
...
@Override
protected void onSaveInstanceState(Bundle outState) {
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
super.onSaveInstanceState(outState);
}
...
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}SupportActivity The statement mLifecycleRegistry object , But it's not directly used for lifecycle distribution , But be ReportFragment adopt activity.getLifecycle() Get use .
ReportFragment
SupportActivity stay onCreate Add... To yourself ReportFragment:
@RestrictTo(LIBRARY_GROUP)
public class SupportActivity extends Activity implements LifecycleOwner {
// ...
@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
// ...
}Low version Activity compatible Lifecycle
SupportActivity It's accompanied by Lifecycle That's what happened ,android.arch.lifecycle:extensions For the early period has not yet inherited SupportActivity Of Activity There is also support , adopt LifecycleDispatcher Realization ReportFragment The injection of :
class LifecycleDispatcher {
static void init(Context context) {
if (sInitialized.getAndSet(true)) {
return;
}
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}
static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
private final FragmentCallback mFragmentCallback;
DispatcherActivityCallback() {
mFragmentCallback = new FragmentCallback();
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (activity instanceof FragmentActivity) {
((FragmentActivity) activity).getSupportFragmentManager()
.registerFragmentLifecycleCallbacks(mFragmentCallback, true);
}
ReportFragment.injectIfNeededIn(activity);
}
}
} I was wondering why ReportFragment The implementation of does not write SupportActivity In the middle , See here, finally understand the meaning of its existence .
LifecycleDispatcher There is no need to Application Call in , He passed ContentProvider Implement initialization
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}
} stay android.arch.lifecycle:extensionsaar Of AndroidManifest Register in :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.arch.lifecycle.extensions" >
<uses-sdk android:minSdkVersion="14" />
<application>
<provider
android:name="android.arch.lifecycle.ProcessLifecycleOwnerInitializer"
android:authorities="${applicationId}.lifecycle-trojan"
android:exported="false"
android:multiprocess="true" />
</application>
</manifest>${applicationId} Place holder , avoid authroities Conflict .
It can be seen that we have achieved the utmost in the matter of non invasion , This noninvasive initialization method is worth learning and using .
Two kinds of Fragment
Through the analysis above , We know Activity It's through ReportFragment Agent LifecycleOwner The implementation of the . So in Activity Added in LifecycleOwner And Activity Of Fragment Is the life cycle consistent ? The answer is No
Android There are two kinds of Fragment There are two kinds of :
- ADK Self contained
android.app.Fragment - Support In bag
android.support.v4.app.Fragment(AndroidX It also falls into this category )
Because the former has been @Deprecated, So the latter is now widely used , That is to say Support perhaps AndroidX Of Fragment. And for the sake of low version compatibility ,ReportFragment It's the former .
Activity For both Fragment The reality of lifecycle callbacks is not the same , With onResume and onStart For example ,Activity The actual callback is shown in the following table :
In the table above () The numbers in represent the order of execution , So you will find ,sdk fragment Of onStart Later than support fragment, and onResume But earlier
Activity Of LifecycleOwner Although it is based on Fragment Realized , But the same Activity Of LifecycleOwner And Fragment The lifecycle callback of is actually not consistent .
This is very important in our development , Don't let Fragment and LifecycleOwner The processing in the life cycle of the process produces temporal dependencies .
summary
* Through source code analysis Activity about LifecycleOwner After the realization of , We come to the following conclusion
- Activity Do not call directly
HandleLifecycleEventDistribution of life cycle , But through ReportFragment Realization - ReportFragment The injection and the whole process are noninvasive , It is worth learning from
- The same Activity, Its
LifecycleOwnerAnd Fragment The lifecycle callback of is actually not consistent , Special attention required
Android Advanced development system notes 、 The latest interview review notes PDF, my GitHub
At the end of the article
Your favorite collection is my greatest encouragement ! Welcome to follow me , Share Android dried food , communication Android technology . What's your opinion on the article , Or any technical problems , Welcome to leave a message and discuss in the comment area !
边栏推荐
- 2021-04-15
- 微信小程序之input调整
- Linear regression analysis of parent-child height data set
- 微信小程序之flex属性
- How to merge tables when exporting excel tables with xlsx
- [deeply understand tcapulusdb technology] tmonitor system upgrade
- Vulnhub target os-hacknos-1
- Best practices for auto plug-ins and automatic batch processing in openvinotm 2022.1
- Networknt:: JSON schema validator source code appreciation
- 微信小程序之在wx:for中绑定事件
猜你喜欢

Flex attribute of wechat applet

Technology sharing | do you understand the requirements of the tested project?

KS008基于SSM的新闻发布系统

Quartus II 13.1 安装步骤详解

In depth analysis of mobilenet and its variants

CRMEB 二开短信功能教程
![[deeply understand tcapulusdb technology] tmonitor system upgrade](/img/22/517556a0cab666eba1434d4c2be2ac.png)
[deeply understand tcapulusdb technology] tmonitor system upgrade

【课程预告】基于飞桨和OpenVINO 的AI表计产业解决方案 | 工业读表与字符检测

使用OpenVINOTM预处理API进一步提升YOLOv5推理性能

前AMD芯片架构师吐槽,取消 K12 处理器项目是因为 AMD 怂了!
随机推荐
The data value reported by DTU cannot be filled into Tencent cloud database through Tencent cloud rule engine
What is the working status of software testing with a monthly salary of 7500
Former amd chip architect roast said that the cancellation of K12 processor project was because amd counseled!
IEEE Transaction期刊修改过程记录
【课程预告】基于飞桨和OpenVINO 的AI表计产业解决方案 | 工业读表与字符检测
Win the championship for 2 consecutive years! ZABBIX ranked first in a number of monitoring software in 2022
Use xtradiagram Diagramcontrol for drawing and controlling process graphics
2022 college entrance examination quarterly essay winners announced
DTU上报的数据值无法通过腾讯云规则引擎填入腾讯云数据库中
AI 参考套件
[Course preview] AI meter industry solution based on propeller and openvino | industrial meter reading and character detection
[deeply understand tcapulusdb technology] tmonitor background one click installation
In depth analysis of mobilenet and its variants
Understand ADT and OOP
Simplify deployment with openvino model server and tensorflow serving
理解ADT与OOP
OpenVINOTM 2022.1中AUTO插件和自动批处理的最佳实践
PHP receiving and sending data
Flex attribute of wechat applet
Oracle进入sqlplus 报错