FgThread类的作用是为系统提供一个运行在前台的共享单例线程,用来执行通用的前台service操作,不会阻塞任何东西
1.FgThread简介
类定义如下:
public final class FgThread extends ServiceThread
几个关键属性
- private static FgThread sInstance FgThread对象
- private static Handler sHandler handler对象,用来处理消息
- private static HandlerExecutor sHandlerExecutor 用来执行任务
ServiceThread类继承自HandlerThread,是一个拥有属于线程自己的Looper对象
public class ServiceThread extends HandlerThread
关于Handler的说明,可以参考android Handler消息机制实现原理
没有对外提供构造方法,私有的构造方法里面,设置了线程名为android.fg
private FgThread() {
super("android.fg", android.os.Process.THREAD_PRIORITY_DEFAULT, true /*allowIo*/);
}
对外提供了3个接口
- get 获取FgThread对象
- getHandler 获取Handler对象
- getExecutor 获取Executor对象
// 单例模式,返回FgThread对象
public static FgThread get() {
synchronized (FgThread.class) {
ensureThreadLocked();
return sInstance;
}
}
public static Handler getHandler() {
synchronized (FgThread.class) {
ensureThreadLocked();
return sHandler;
}
}
public static Executor getExecutor() {
synchronized (FgThread.class) {
ensureThreadLocked();
return sHandlerExecutor;
}
}
// 初始化sInstance、sHandler和sHandlerExecutor对象,启动线程
private static void ensureThreadLocked() {
if (sInstance == null) {
sInstance = new FgThread();
sInstance.start();
final Looper looper = sInstance.getLooper();
looper.setTraceTag(Trace.TRACE_TAG_SYSTEM_SERVER);
looper.setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
sHandler = new Handler(sInstance.getLooper());
sHandlerExecutor = new HandlerExecutor(sHandler);
}
}
2.FgThread使用分析
以 android RoleManagerService 里面描述的场景为用例说明
getOrCreateController(userId).grantDefaultRoles(FgThread.getExecutor(),
successful -> {
if (successful) {
userState.setPackagesHash(packagesHash);
result.complete(null);
} else {
result.completeExceptionally(new RuntimeException());
}
});
通过FgThread.getExecutor()方法获取HandlerExecutor对象
public class HandlerExecutor implements Executor {
private final Handler mHandler;
public HandlerExecutor(@NonNull Handler handler) {
mHandler = Preconditions.checkNotNull(handler);
}
@Override
public void execute(Runnable command) {
if (!mHandler.post(command)) {
throw new RejectedExecutionException(mHandler + " is shutting down");
}
}
}
其execute方法,就是将传入的Runnable对象发送给mHandler来执行,是在ensureThreadLocked方法里面会传入的Handler对象,Looper是FgThread,最终运行在FgThread线程里面
总结一下FgThread的使用:
通过getExecutor方法来获取一个HandlerExecutor,然后将任务发送给HandlerExecutor来执行,最终在FgThread线程里面执行
FgThread没有定义退出Looper的方式,会一直循环等待消息并执行任务