Lifecycle不仅能感知Activity的生命周期,也能感知Service和Application的生命周期
引入依赖,拓展Lifecycle功能
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0
Lifecycle+Service
1,服务类继承LifecycleService
public class LifeService extends LifecycleService {
private String TAG = "LifeService";
private CustomObserver observer;
public LifeService() {
observer = new CustomObserver();
// 将观察者和被观察者绑定
getLifecycle().addObserver(observer);
}
@Override
public void onCreate() {
super.onCreate();
LogUtil.e(TAG, "onCreate");
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
LogUtil.e(TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(@NonNull Intent intent) {
LogUtil.e(TAG, "onBind");
return super.onBind(intent);
}
@Override
public boolean onUnbind(Intent intent) {
LogUtil.e(TAG, "onUnbind");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
LogUtil.e(TAG, "onDestroy");
}
}
2,开启及关闭服务,得到日志
打开服务
LifeService: onCreate
CustomObserver: Observer ON_CREATE
LifeService: onStartCommand
CustomObserver: Observer ON_START
关闭服务
CustomObserver: Observer ON_STOP
LifeService: onDestroy
CustomObserver: Observer ON_DESTROY
3,LifecycleService做了感知功能
package androidx.lifecycle;
public class LifecycleService extends Service implements LifecycleOwner {
private final ServiceLifecycleDispatcher mDispatcher = new ServiceLifecycleDispatcher(this);
@CallSuper
@Override
public void onCreate() {
mDispatcher.onServicePreSuperOnCreate();
super.onCreate();
}
@CallSuper
@Nullable
@Override
public IBinder onBind(@NonNull Intent intent) {
mDispatcher.onServicePreSuperOnBind();
return null;
}
@SuppressWarnings("deprecation")
@CallSuper
@Override
public void onStart(@Nullable Intent intent, int startId) {
mDispatcher.onServicePreSuperOnStart();
super.onStart(intent, startId);
}
@CallSuper
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@CallSuper
@Override
public void onDestroy() {
mDispatcher.onServicePreSuperOnDestroy();
super.onDestroy();
}
@Override
@NonNull
public Lifecycle getLifecycle() {
return mDispatcher.getLifecycle();
}
}
4,LifecycleService全靠ServiceLifecycleDispatcher进行事件传递
package androidx.lifecycle;
public class ServiceLifecycleDispatcher {
private final LifecycleRegistry mRegistry;
private final Handler mHandler;
private DispatchRunnable mLastDispatchRunnable;
public ServiceLifecycleDispatcher(@NonNull LifecycleOwner provider) {
mRegistry = new LifecycleRegistry(provider);
mHandler = new Handler();
}
private void postDispatchRunnable(Lifecycle.Event event) {
if (mLastDispatchRunnable != null) {
mLastDispatchRunnable.run();
}
mLastDispatchRunnable = new DispatchRunnable(mRegistry, event);
mHandler.postAtFrontOfQueue(mLastDispatchRunnable);
}
public void onServicePreSuperOnCreate() {
postDispatchRunnable(Lifecycle.Event.ON_CREATE);
}
public void onServicePreSuperOnBind() {
postDispatchRunnable(Lifecycle.Event.ON_START);
}
public void onServicePreSuperOnStart() {
postDispatchRunnable(Lifecycle.Event.ON_START);
}
public void onServicePreSuperOnDestroy() {
postDispatchRunnable(Lifecycle.Event.ON_STOP);
postDispatchRunnable(Lifecycle.Event.ON_DESTROY);
}
@NonNull
public Lifecycle getLifecycle() {
return mRegistry;
}
static class DispatchRunnable implements Runnable {
private final LifecycleRegistry mRegistry;
final Lifecycle.Event mEvent;
private boolean mWasExecuted = false;
DispatchRunnable(@NonNull LifecycleRegistry registry, Lifecycle.Event event) {
mRegistry = registry;
mEvent = event;
}
@Override
public void run() {
if (!mWasExecuted) {
mRegistry.handleLifecycleEvent(mEvent);
mWasExecuted = true;
}
}
}
}
5,ServiceLifecycleDispatcher里有我们熟悉的LifecycleRegistry,负责处理后续事宜
比较特别的
1,onServicePreSuperOnDestroy()会触发Lifecycle.Event.ON_STOP和Lifecycle.Event.ON_DESTROY,因为Service本身没有stop()所以一起发送了
2,OnBind和OnStart都回触发Lifecycle.Event.ON_START
总结:
Service+Lifecycle的实现相当简单,LifecycleRegistry的封装类-ServiceLifecycleDispatcher在LifecycleService的各个生命方法中将事件传给LifecycleRegistry来处理,后面的操作和Activity是一样的。
Lifecycle+Application
1,在Application添加观察者
public class MyApplication extends BaseApplication {
@Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(new CustomObserver());
}
}
2,通过进去app/退出app/重新进入app,得到日志
进入app
CustomObserver: Observer ON_CREATE
CustomObserver: Observer ON_START
CustomObserver: Observer ON_RESUME
退出app到Home页
CustomObserver: Observer ON_PAUSE
CustomObserver: Observer ON_STOP
重新进入app
CustomObserver: Observer ON_START
CustomObserver: Observer ON_RESUME
挂起app,然后划掉杀死app进程
CustomObserver: Observer ON_PAUSE
CustomObserver: Observer ON_STOP
关键在于ProcessLifecycleOwner
源码分析:
1,首先我们看一下Application的源码,除了一个onCreate()和一些跟activity生命周期回调/监听和内存状态操作回调的方法外,并没有其他相关的生命周期方法
2,我们知道,一个应用中,application的生命是最长的,但却只体现在创建创建/前台/后台/销毁,其中销毁是被动的不会有打日志的机会.
3,实际上ProcessLifecycleOwner是监听每个activity的生命周期,通过计数的形式判断application的生命状态
下面根据ProcessLifecycleOwner中的LifecycleRegistry实例分析上述log
package androidx.lifecycle;
@SuppressWarnings("WeakerAccess")
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();
}
};
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();
@NonNull
public static LifecycleOwner get() {
return sInstance;
}
static void init(Context context) {//在androidx.lifecycle.ProcessLifecycleOwnerInitializer中调用,进行ProcessLifecycleOwner的开始
sInstance.attach(context);
}
void activityStarted() {
mStartedCounter++;
if (mStartedCounter == 1 && mStopSent) {//由0自增到1,表示app到前台状态了
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
mStopSent = false;
}
}
void activityResumed() {
mResumedCounter++;
if (mResumedCounter == 1) {//由0自增到1,表示app到前台状态了
if (mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
mPauseSent = false;
} else {
mHandler.removeCallbacks(mDelayedPauseRunnable);
}
}
}
void activityPaused() {//由1自减到0,表示app到后台状态了
mResumedCounter--;
if (mResumedCounter == 0) {
mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);
}
}
void activityStopped() {
mStartedCounter--;
dispatchStopIfNeeded();
}
void dispatchPauseIfNeeded() {
if (mResumedCounter == 0) {表示app到后台状态了
mPauseSent = true;
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
}
}
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() {//监听activity的各生命周期方法,并进行后续操作
@Override
public void onActivityPreCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
activity.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@Override
public void onActivityPostStarted(@NonNull Activity activity) {
activityStarted();//监听onStart()
}
@Override
public void onActivityPostResumed(@NonNull Activity activity) {
activityResumed();//监听onResume()
}
});
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT < 29) {
ReportFragment.get(activity).setProcessListener(mInitializationListener);
}
}
@Override
public void onActivityPaused(Activity activity) {
activityPaused();//监听onPause()
}
@Override
public void onActivityStopped(Activity activity) {
activityStopped();//监听onStop()
}
});
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mRegistry;
}
}
通过对mStartedCounter和mResumedCounter的变化及是否等于1或者等于0来判断状态,判断application的状态。
再有,ProcessLifecycleOwner是androidx.lifecycle下面的类,这个类并不是Android原始系统的代码,那它是如何实现随着app启动时而启动呢,答案是新建了一个空的ContentProvider。androidx.lifecycle下面,有一个空白的contentprovider----ProcessLifecycleOwnerInitializer。
package androidx.lifecycle;
@SuppressWarnings("UnknownNullness")
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());//在此处调用ProcessLifecycleOwner
return true;
}
...
}
而contentprovider是随着系统启动自动执行的,甚至早于application的onCreate()
android.app.ActivityThread
private void handleBindApplication(AppBindData data) {
......
if (!data.restrictedBackupMode) {
if (!ArrayUtils.isEmpty(data.providers)) {
installContentProviders(app, data.providers);//安装注册所有的contentprovider
}
}
// Do this after providers, since instrumentation tests generally start their
// test thread at this point, and we don't want that racing.
try {
mInstrumentation.onCreate(data.instrumentationArgs);
}
catch (Exception e) {
......
}
try {
mInstrumentation.callApplicationOnCreate(app);//调用application的OnCreate()
} catch (Exception e) {
......
}
}
......
}
这样就完美实现了在不干扰原有Android原始代码上拓展了监听application的生命状态,引用了这个Lifecycle的依赖就自动添加了此contentprovider,也就自动加载ProcessLifecycleOwner,也就能根据activity判断和感知application的状态。
后续的感知状态状态后事件发送给观察者,和之前activity的流程是一样的。
总结:
Lifecycle在Service和Application上的使用已经介绍完毕,并在源码上分析了是如何感知生命周期的,有些设计是相当神奇的,值得平时开发参考,Lifecycle在fragment中的使用没有太大的难度,androidx的fragment在类中就实现了感知生命状态,没那么多弯弯道道,就不展开分析了。
至此,Lifecycle的全部场景已经分析完毕,后续进行其他组件的分析。
Android-Jetpack代码位置:github