学习Lifecycle-Service
西北工业大学 开源群智作业
一、LifecycleService
LifecycleOwner 接口用于标记其实现类具备 Lifecycle 对象,即具备生命周期。而四大组件之一的 Service 本身从被启动/绑定再到被停止,具有着类似 Activity / Fragment 从前台到退出页面之间的一系列行为。
所以 Jetpack 也提供了 LifecycleService 这个 Service 的子类,用于监听 Service 的生命周期活动。
LifecycleService 是在各个生命周期函数中将当前的 Event 事件转发给 ServiceLifecycleDispatcher 进行处理,由其来进行具体的事件分发。
当中,为了兼顾 startService 和 bindService 两种不同的情况,onBind和onStart所触发的均是 Lifecycle.Event.ON_START事件,这是为了兼顾startService和bindService 两种不同的情况
/*
* Copyright (C) 2017 The Android Open Source Project
*
* 根据Apache许可证,2.0版("许可证")许可。
* 除非遵守许可证的规定,否则你不得使用此文件。
* 你可以在以下地址获得一份许可证的副本
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 除非适用法律要求或书面同意,
* 根据本许可证分发的软件是按 "原样 "分发的,
* 没有任何形式的保证或条件,无论是明示还是暗示。
*/
package androidx.lifecycle;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* 一个同时是{@link LifecycleOwner}的服务。
*/
public class LifecycleService extends Service implements LifecycleOwner {
private final ServiceLifecycleDispatcher mDispatcher = new ServiceLifecycleDispatcher(this);
/**
* 创建LifeCycle时发生的事件,LifeCycle到Created状态
* 触发Lifecycle.Event.ON_CREATE 事件
*/
@CallSuper
@Override
public void onCreate() {
// 将当前的 Event 事件转发给 ServiceLifecycleDispatcher 进行处理
mDispatcher.onServicePreSuperOnCreate();
super.onCreate();
}
/**
* 事件绑定到LifeCycle
* 触发Lifecycle.Event.ON_START 事件
* @param intent intent
* @return null
*/
@CallSuper
@Nullable
@Override
public IBinder onBind(@NonNull Intent intent) {
// 将当前的 Event 事件转发给 ServiceLifecycleDispatcher 进行处理
mDispatcher.onServicePreSuperOnBind();
return null;
}
/**
* 从Created状态到Started状态发生的事件
* @param intent intent
* @param startId 当前服务的唯一ID
*/
@SuppressWarnings("deprecation")
@CallSuper
@Override
public void onStart(@Nullable Intent intent, int startId) {
// 将当前的 Event 事件转发给 ServiceLifecycleDispatcher 进行处理
mDispatcher.onServicePreSuperOnStart();
super.onStart(intent, startId);
}
/**
* 添加这个方法只是为了用@CallSuper来注释它。
* 在通常的服务中,super.onStartCommand是没有作用的,
* 但是在LifecycleService中,它导致了mDispatcher.onServicePreSuperOnStart()的调用,
* 因为 super.onStartCommand调用onStart()。
*
* @param intent 启动时,启动组件传递过来的Intent,如Activity可利用Intent封装所需要的参数并传递给Service。
* @param flags 表示启动请求时是否有额外数据,可选值有 0,START_FLAG_REDELIVERY,START_FLAG_RETRY
* @param startId 当前服务的唯一ID,与stopSelfResult(int startId)配合使用,stopSelfResult() 可以更安全地根据ID停止服务。
* @return 4种返回值
* 1.TART_STICKY —— 如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。
* 随后系统会尝试重新创建servic,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null。
* 2.START_NOT_STICKY —— 使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。
* 3.START_REDELIVER_INTENT —— 重传Intent,使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。
* 4.START_STICKY_COMPATIBILITY —— START_STICKY的兼容版本,但不保证服务被kill后一定能重启。
*/
@CallSuper
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
// 调用onStartCommand(intent, flags, startId)
return super.onStartCommand(intent, flags, startId);
}
/**
* 从Stopped状态到Destroyed状态时发生的事件
* 触发Lifecycle.Event.ON_STOP 和 Lifecycle.Event.ON_DESTORY 事件
*
* 为了用@CallSuper来注释它。
* 在LifecycleService中,它导致了mDispatcher.onServicePreSuperOnDestroy()的调用
*/
@CallSuper
@Override
public void onDestroy() {
// 将当前的 Event 事件转发给 ServiceLifecycleDispatcher 进行处理
mDispatcher.onServicePreSuperOnDestroy();
super.onDestroy();
}
/**
* 得到LifeCycle
* @return LifeCycle
*/
@Override
@NonNull
public Lifecycle getLifecycle() {
// 将当前的 Event 事件转发给 ServiceLifecycleDispatcher 进行处理
return mDispatcher.getLifecycle();
}
}
二、 继承的Service(服务)概述
Service是Android系统中的四大组件之一。
Service是可以在后台执行长时间运行操作而没有用户界面的应用组件。服务可由其他应用组件启动(如Activity),服务一旦被启动将在后台一直运行,即使启动服务的组件(Activity)已销毁也不受影响,除非系统必须回收内存资源,否则系统不会停止或销毁Service。
服务基本上分为两种形式:
-
startService
当应用组件(如 Activity)通过调用 startService() 启动服务时,服务即处于“start”状态。一旦启动,服务即可在后台无限期运行,即使启动服务的组件已被销毁也不受影响。 已启动的服务通常是执行单一操作,而且不会将结果返回给调用方。例如,它可能通过网络下载或上传文件。 操作完成后,服务会自行停止运行。
-
bindService
当应用组件通过调用 bindService() 绑定到服务时,服务即处于“bind”状态。绑定服务提供了一个客户端-服务器接口,允许组件与服务进行交互、发送请求、获取结果,甚至是利用进程间通信 (IPC) 跨进程执行这些操作。 仅当与另一个应用组件绑定时,绑定服务才会运行。 多个组件可以同时绑定到该服务,但全部取消绑定后,该服务即会被销毁。
生命周期
三、ServiceLifecycleDispatcher
ServiceLifecycleDispatcher 将每一次的 Event 事件都包装为 DispatchRunnable 对象,然后转交由 mHandler 来执行。
此外,为了保证 Lifecycle.Event 能被及时触发并保证有序性,postDispatchRunnable()方法会主动调用mLastDispatchRunnable对象的 run() 方法(如果不为 null 的话)。
因为交由 Handler 执行的 Runnable 并不是可以保证就是实时完成的,为了保证 Event 值的有序性就会在有新 Event 到来时主动调用 run() 方法
ServiceLifecycleDispatcher 的逻辑内部也使用到了 LifecycleRegistry 作为 LifecycleService 的getLifecycle() 方法的返回值,这点和 androidx.appcompat.app.AppCompatActivity 和 androidx.fragment.app.Fragment 保持一致
/*
* Copyright (C) 2017 The Android Open Source Project
*
* 根据Apache许可证,2.0版("许可证")许可。
* 除非遵守许可证的规定,否则你不得使用此文件。
* 你可以在以下地址获得一份许可证的副本
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 除非适用法律要求或书面同意,
* 根据本许可证分发的软件是按 "原样 "分发的,
* 没有任何形式的保证或条件,无论是明示还是暗示。
*/
package androidx.lifecycle;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import androidx.annotation.NonNull;
/**
* 帮助类,用于转发调度服务的生命周期事件。
* 只有可能使用{@link LifecycleService}的情况下,才使用本类。
*/
@SuppressWarnings("WeakerAccess")
public class ServiceLifecycleDispatcher {
// LifecycleRegistry
private final LifecycleRegistry mRegistry;
// Handler
private final Handler mHandler;
// DispatchRunnable 转发调度线程
private DispatchRunnable mLastDispatchRunnable;
/**
* @param provider {@link LifecycleOwner} for a service, usually it is a service itself
*/
@SuppressWarnings("deprecation")
public ServiceLifecycleDispatcher(@NonNull LifecycleOwner provider) {
mRegistry = new LifecycleRegistry(provider);
mHandler = new Handler();
}
private void postDispatchRunnable(Lifecycle.Event event) {
if (mLastDispatchRunnable != null) {
// 线程run()
mLastDispatchRunnable.run();
}
mLastDispatchRunnable = new DispatchRunnable(mRegistry, event);
mHandler.postAtFrontOfQueue(mLastDispatchRunnable);
}
/**
* 触发Lifecycle.Event.ON_CREATE 事件
*
* 必须是{@link Service#onCreate()}方法的第一次调用,
* 甚至在super.onCreate调用之前。
*/
public void onServicePreSuperOnCreate() {
postDispatchRunnable(Lifecycle.Event.ON_CREATE);
}
/**
* 触发Lifecycle.Event.ON_START 事件
*
* 必须是{@link Service#onBind(Intent)}方法的第一次调用,甚至在super.onBind调用之前。
*/
public void onServicePreSuperOnBind() {
postDispatchRunnable(Lifecycle.Event.ON_START);
}
/**
* 触发Lifecycle.Event.ON_START 事件
*
* 必须是{@link Service#onStart(Intent, int)}或{@link Service#onStartCommand(Intent, int)}方法中的第一个调用。
* {@link Service#onStartCommand(Intent, int, int)}方法中的第一次调用,甚至在相应的父类调用之前。
*/
public void onServicePreSuperOnStart() {
postDispatchRunnable(Lifecycle.Event.ON_START);
}
/**
* 触发Lifecycle.Event.ON_STOP 事件
* 触发Lifecycle.Event.ON_DESTORY 事件
*
* 必须是{@link Service#onDestroy()}方法的第一次调用,
* 甚至在super.OnDestroy调用之前。
*/
public void onServicePreSuperOnDestroy() {
// 触发Lifecycle.Event.ON_STOP 事件
postDispatchRunnable(Lifecycle.Event.ON_STOP);
// 触发Lifecycle.Event.ON_DESTORY 事件
postDispatchRunnable(Lifecycle.Event.ON_DESTROY);
}
/**
* @return 给定的{@link LifecycleOwner}的{@link Lifecycle}。
*/
@NonNull
public Lifecycle getLifecycle() {
return mRegistry;
}
static class DispatchRunnable implements Runnable {
// LifecycleRegistry
private final LifecycleRegistry mRegistry;
// Lifecycle.Event
final Lifecycle.Event mEvent;
// Lifecycle.Event处理了吗
private boolean mWasExecuted = false;
DispatchRunnable(@NonNull LifecycleRegistry registry, Lifecycle.Event event) {
mRegistry = registry;
mEvent = event;
}
@Override
public void run() {
if (!mWasExecuted) {
// LifecycleRegistry处理Lifecycle.Event
mRegistry.handleLifecycleEvent(mEvent);
mWasExecuted = true;
}
}
}
}