Arouter
源码分析系列文章,请访问https://github.com/AlexMahao/ARouter
在分析路由跳转时,最终的跳转会判断是否是绿色通道,如果不是,将会走拦截器相关的逻辑。
// 如果不是绿色通多,拦截器做拦截
if (!postcard.isGreenChannel()) {
// It must be run in async thread, maybe interceptor cost too mush time made ANR.
interceptorService.doInterceptions(postcard, new InterceptorCallback() {
/**
* Continue process
*
* @param postcard route meta
*/
@Override
public void onContinue(Postcard postcard) {
_navigation(context, postcard, requestCode, callback);
}
/**
* Interrupt process, pipeline will be destory when this method called.
*
* @param exception Reson of interrupt.
*/
@Override
public void onInterrupt(Throwable exception) {
if (null != callback) {
callback.onInterrupt(postcard);
}
logger.info(Consts.TAG, "Navigation failed, termination by interceptor : " + exception.getMessage());
}
});
} else {
return _navigation(context, postcard, requestCode, callback);
}
那么拦截器到底是怎么实现的呢?
逻辑分析
官方demo如下:
@Interceptor(priority = 7)
public class Test1Interceptor implements IInterceptor {
}
- 编译时期生成拦截器辅助类
- 初始化时期加载拦截器辅助类,并初始化拦截器服务。
- 跳转时期进行拦截器执行
编译时期生成辅助工具类
编译时期通过apt
对@Interceptor
做处理,生成拦截器辅助类。处理类为InterceptorProcessor
。逻辑比较简单,看一下生成的辅助类代码:
public class ARouter$$Interceptors$$app implements IInterceptorGroup {
@Override
public void loadInto(Map<Integer, Class<? extends IInterceptor>> interceptors) {
interceptors.put(7, Test1Interceptor.class);
}
}
该辅助类就是将拦截器的类存入到一个集合中去。其中key
是声明的拦截器的优先级。
初始化时期加载拦截器
在之前分析路由跳转时,加载路由表到Warehouse
中存储是通过LogisticsCenter.init()
方法,该方法中获取com.alibaba.android.arouter.routes
下面的所有类,其中包含了Interceptors
的辅助类。在该方法中加载辅助类并将Interceptor
存储到Warehouse
中。
public synchronized static void init(Context context, ThreadPoolExecutor tpe) throws HandlerException {
try {
// ....
if (registerByPlugin) {
logger.info(TAG, "Load router map by arouter-auto-register plugin.");
} else {
Set<String> routerMap;
for (String className : routerMap) {