首先从Lifecycle的manifests文件说起:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.arch.lifecycle.extensions"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="26" />
<application>
<provider
android:name="android.arch.lifecycle.LifecycleRuntimeTrojanProvider"
android:authorities="${applicationId}.lifecycle-trojan"
android:exported="false"
android:multiprocess="true" />
application>
manifest>
Lifecycle框架会在应用的manifest文件中添加一个provider(LifecycleRuntimeTrojanProvider)。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.persistence">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
<application
android:name=".viewmodel.MyApplication"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="com.example.android.persistence.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER" />
intent-filter>
activity>
application>
manifest>
通过apktool拿到的最终apk中的manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.persistence" platformBuildVersionCode="26" platformBuildVersionName="8.0.0">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.location.gps"/>
<application android:allowBackup="false" android:debuggable="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme">
<activity android:name="com.example.android.persistence.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
intent-filter>
activity>
<meta-data android:name="android.support.VERSION" android:value="26.0.2"/>
<provider android:authorities="com.example.android.persistence.lifecycle-trojan" android:exported="false" android:multiprocess="true" android:name="android.arch.lifecycle.LifecycleRuntimeTrojanProvider"/>
application>
manifest>
可以看到lifecycle框架会向应用中添加一个LifecycleRuntimeTrojanProvider,而这个provider只是为了启动lifecycle框架。接下来我们看一下LifecycleRuntimeTrojanProvider。
public class LifecycleRuntimeTrojanProvider extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, String[] strings, String s, String[] strings1,
String s1) {
return null;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, ContentValues contentValues) {
return null;
}
@Override
public int delete(@NonNull Uri uri, String s, String[] strings) {
return 0;
}
@Override
public int update(@NonNull Uri uri, ContentValues contentValues, String s, String[] strings) {
return 0;
}
}
可以看到除了onCreate方法,其他都是返回null或0。初始化方法中
一个是初始化lifecycle框架,一个是创建了ProcessLifecycleOwner来监听进程的lifecycle。
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
先看LifecycleDispatcher.init(getContext());
class LifecycleDispatcher {
private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
private static AtomicBoolean sInitialized = new AtomicBoolean(false);
static void init(Context context) {
if (sInitialized.getAndSet(true)) {
return;
}
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}
...
}
在init中注册了activitylifecyclecallback,在onActivityCreated中又注册了fragmentLifecycleCallback。onActivityStopped和onActivitySaveInstanceState中发送CREATED状态。(可以参考lifecycle状态图)。
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);
}
@Override
public void onActivityStopped(Activity activity) {
if (activity instanceof FragmentActivity) {
markState((FragmentActivity) activity, CREATED);
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
if (activity instanceof FragmentActivity) {
markState((FragmentActivity) activity, CREATED);
}
}
}
在fragmentLifecycleCallback的onFragmentCreated回调中又添加了一个空的DestructionReportFragment。fragmentLifecycleCallback用来监听onCreate、onStart、onResume事件。
static class FragmentCallback extends FragmentManager.FragmentLifecycleCallbacks {
@Override
public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {
dispatchIfLifecycleOwner(f, ON_CREATE);
if (!(f instanceof LifecycleRegistryOwner)) {
return;
}
if (f.getChildFragmentManager().findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
f.getChildFragmentManager().beginTransaction().add(new DestructionReportFragment(),
REPORT_FRAGMENT_TAG).commit();
}
}
@Override
public void onFragmentStarted(FragmentManager fm, Fragment f) {
dispatchIfLifecycleOwner(f, ON_START);
}
@Override
public void onFragmentResumed(FragmentManager fm, Fragment f) {
dispatchIfLifecycleOwner(f, ON_RESUME);
}
}
空的DestructionReportFragment用来监听onPause、onStop、onDestroy事件。
public static class DestructionReportFragment extends Fragment {
@Override
public void onPause() {
super.onPause();
dispatch(ON_PAUSE);
}
@Override
public void onStop() {
super.onStop();
dispatch(ON_STOP);
}
@Override
public void onDestroy() {
super.onDestroy();
dispatch(ON_DESTROY);
}
protected void dispatch(Lifecycle.Event event) {
dispatchIfLifecycleOwner(getParentFragment(), event);
}
}
这块总结一下
1. 注册registerActivityLifecycleCallbacks,onActivityCreated方法中注册registerFragmentLifecycleCallbacks。onActivityStopped和onActivitySaveInstanceState中发送CREATED状态。
2. FragmentCallback在onFragmentCreated发送ON_CREATE事件;onFragmentStarted发送ON_START;onFragmentResumed发送ON_RESUME事件。同时onFragmentCreated中添加DestructionReportFragment(用来监听onPause、onStop、onDestroy)。
可以看到lifecycle用FragmentCallback和DestructionReportFragment结合的方式来监听生命周期。这么做的目的应该是为了onCreate、onStart、onResume事件发生在activity相应回调之后,onPause、onStop、onDestroy事件发生在相应回调之前。(调试发现FragmentCallback的方法会多次回调,并且FragmentCallback的onFragmentStarted还是发生在了activity的onStart之前)
ActivityLifecycleCallbacks的onActivityCreated方法中还有一句:
ReportFragment.injectIfNeededIn(activity);
前面的分析是在if (activity instanceof FragmentActivity) ,也就是在应用中采用的是FragmentActivity的前提下进行了,有可能应用中用的是app包中的Activity,所以这里对这种情况进行处理。
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();
}
}
在这种情况下会添加一个空的ReportFragment,在onActivityCreated、onStart、onResume、onPause、onStop、onDestroy中发送相应的生命周期事件。
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
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();
}
}
static ReportFragment get(Activity activity) {
return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
REPORT_FRAGMENT_TAG);
}
private ActivityInitializationListener mProcessListener;
private void dispatchCreate(ActivityInitializationListener listener) {
if (listener != null) {
listener.onCreate();
}
}
private void dispatchStart(ActivityInitializationListener listener) {
if (listener != null) {
listener.onStart();
}
}
private void dispatchResume(ActivityInitializationListener listener) {
if (listener != null) {
listener.onResume();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
dispatchResume(mProcessListener);
dispatch(Lifecycle.Event.ON_RESUME);
}
@Override
public void onPause() {
super.onPause();
dispatch(Lifecycle.Event.ON_PAUSE);
}
@Override
public void onStop() {
super.onStop();
dispatch(Lifecycle.Event.ON_STOP);
}
@Override
public void onDestroy() {
super.onDestroy();
dispatch(Lifecycle.Event.ON_DESTROY);
// just want to be sure that we won't leak reference to an activity
mProcessListener = null;
}
private void dispatch(Lifecycle.Event event) {
if (getActivity() instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) getActivity()).getLifecycle().handleLifecycleEvent(event);
}
}
void setProcessListener(ActivityInitializationListener processListener) {
mProcessListener = processListener;
}
interface ActivityInitializationListener {
void onCreate();
void onStart();
void onResume();
}
}
可以看到在onActivityCreated、onStart、onStop中除了dispatch(Lifecycle.Event.xx);还多了dispatchXX(mProcessListener);方法。这个mProcessListener从名字也可以看出,是ProcessLifecycleOwner用来监听有activity真正的进入到激活状态的。
接下来我们分析下ProcessLifecycleOwner。
public class ProcessLifecycleOwner implements LifecycleOwner {
@VisibleForTesting
static final long TIMEOUT_MS = 700; //mls
// ground truth counters
private int mStartedCounter = 0;
private int mResumedCounter = 0;
private boolean mPauseSent = true;
private boolean mStopSent = true;
private Handler mHandler;
private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);
private Runnable mDelayedPauseRunnable = new Runnable() {
@Override
public void run() {
dispatchPauseIfNeeded();
dispatchStopIfNeeded();
}
};
private ActivityInitializationListener mInitializationListener =
new ActivityInitializationListener() {
@Override
public void onCreate() {
}
@Override
public void onStart() {
activityStarted();
}
@Override
public void onResume() {
activityResumed();
}
};
private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner();
/**
* The LifecycleOwner for the whole application process. Note that if your application
* has multiple processes, this provider does not know about other processes.
*
* @return {@link LifecycleOwner} for the whole application.
*/
public static LifecycleOwner get() {
return sInstance;
}
static void init(Context context) {
sInstance.attach(context);
}
void activityStarted() {
mStartedCounter++;
if (mStartedCounter == 1 && mStopSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
mStopSent = false;
}
}
void activityResumed() {
mResumedCounter++;
if (mResumedCounter == 1) {
if (mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
mPauseSent = false;
} else {
mHandler.removeCallbacks(mDelayedPauseRunnable);
}
}
}
void activityPaused() {
mResumedCounter--;
if (mResumedCounter == 0) {
mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);
}
}
void activityStopped() {
mStartedCounter--;
dispatchStopIfNeeded();
}
private void dispatchPauseIfNeeded() {
if (mResumedCounter == 0) {
mPauseSent = true;
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
}
}
private void dispatchStopIfNeeded() {
if (mStartedCounter == 0 && mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
mStopSent = true;
}
}
private ProcessLifecycleOwner() {
}
void attach(Context context) {
mHandler = new Handler();
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
Application app = (Application) context.getApplicationContext();
app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
ReportFragment .get(activity).setProcessListener(mInitializationListener);
}
@Override
public void onActivityPaused(Activity activity) {
activityPaused();
}
@Override
public void onActivityStopped(Activity activity) {
activityStopped();
}
});
}
@Override
public Lifecycle getLifecycle() {
return mRegistry;
}
}
可以看到ProcessLifecycleOwner代码比较清晰了,onStart和onResume是由上面分析的ReportFragment的对应回调发送过来的,保证activity真正的被启动。而onPause和onStop是由自己注册的ActivityLifecycleCallbacks回调的。
void attach(Context context) {
mHandler = new Handler();
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
Application app = (Application) context.getApplicationContext();
app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
ReportFragment .get(activity).setProcessListener(mInitializationListener);
}
@Override
public void onActivityPaused(Activity activity) {
activityPaused();
}
@Override
public void onActivityStopped(Activity activity) {
activityStopped();
}
});
}
onActivityCreated中设置了listenerReportFragment .get(activity).setProcessListener(mInitializationListener);
private ActivityInitializationListener mInitializationListener =
new ActivityInitializationListener() {
@Override
public void onCreate() {
}
@Override
public void onStart() {
activityStarted();
}
@Override
public void onResume() {
activityResumed();
}
};
不论是ReportFragment回调的onStart、onResume还是自己注册回调的onPause、onStop最终都调用相应的activityXX方法。
ProcessLifecycleOwner利用两个counter计算当前活着的activity数量
// ground truth counters
private int mStartedCounter = 0;
private int mResumedCounter = 0;
比较有意思的是pause和stop中加了个700ms的延时。这个延时足以保证ProcessLifecycleOwner在activities销毁或者因为配置变化重建的时候不会发送任何事件。
void activityPaused() {
mResumedCounter--;
if (mResumedCounter == 0) {
mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);
}
}
void activityStopped() {
mStartedCounter--;
dispatchStopIfNeeded();
}
private void dispatchPauseIfNeeded() {
if (mResumedCounter == 0) {
mPauseSent = true;
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
}
}