我们都知道Activity可作为LifecycleOwner
为LiveData的使用提供条件,那么Activity是如何实现LifecycleOwner的呢?
Activity虽然实现了LifecycleOwner接口,但是并没有实现相关处理,而是通过添加一个Fragment来代理Lifecycle的分发。这种通过Fragment代理Activity行为的设计在其他一些库也经常出现,相对来说更加无侵和优雅。
Activity通过继承SupportActivity
实现LifecycleOwner接口。注意在AndroidX中SupportActivity改名为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声明了mLifecycleRegistry
对象,但是没有直接使用其进行生命周期的分发,而是被ReportFragment
通过activity.getLifecycle()
获取使用。
SupportActivity在onCreate
为自己添加了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);
}
// ...
}
injectIfNeededIn
是ReportFragment的静态方法
public static void injectIfNeededIn(Activity activity) {
// ProcessLifecycleOwner should always correctly work and some activities may not extend
// FragmentActivity from support lib, so we use framework fragments for activities
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();
}
}
SupportActivity是伴随Lifecycle才出现的,android.arch.lifecycle:extensions
为早期还没有继承SupportActivity的Activity也提供了支持,通过LifecycleDispatcher
实现ReportFragment的注入:
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);
}
}
}
之前还疑惑为什么ReportFragment的实现不写到SupportActivity中去,看到这里终于理解了其存在的意义了吧。
LifecycleDispatcher
并不需要在Application中调用,他通过ContentProvider
实现初始化
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}
}
在android.arch.lifecycle:extensions
aar的AndroidManifest中注册:
<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}
占位符,避免authroities冲突。
可见在无侵这件事情上做到了极致,这种无侵的初始化方法非常值得我们借鉴和使用。
通过上面分析,我们知道Activity是通过ReportFragment代理了LifecycleOwner的实现。那么在Activity中添加的LifecycleOwner
与Activity的Fragment
的生命周期是否一致呢?答案是否定的
Android中存在两种Fragment有两种:
android.app.Fragment
android.support.v4.app.Fragment
(AndroidX也归为此类)由于前者已经被@Deprecated
,所以现在普遍使用的是后者,也就是Support或者AndroidX的Fragment。而出于低版本兼容性的考虑,ReportFragment
是前者。
Activity对于两种Fragment生命周期回调的实际并不相同,以onResume
和onStart
为例,Activity回调的实际如下表:
onStart | onResume | |
---|---|---|
adk fragment | Activity.performStart(2) | Activity.onResume(3) |
support fragment | Activity.onStart(1) | Activity.onPostResume(4) |
上面表格中()
中的数字表示依次执行的顺序,所以你会发现,adk fragment的onStart
晚于support fragment,而onResume
确更早执行
Activity的LifecycleOwner虽然是基于Fragment实现的,但是同一个Activity的LifecycleOwner与Fragment的生命周期回调实际并不一致。
这在我们的开发重要特备注意,不要视图让Fragment和LifecycleOwner的生命周期中的处理产生时序上的依赖关系。
通过源码分析Activity对于LifecycleOwner的实现后,我们得到以下结论
HandleLifecycleEvent
进行生命周期的分发,而是通过ReportFragment
实现LifecycleOwner
与Fragment的生命周期回调实际并不一致,需要特别注意