ARouter源码分析(二)—— 拦截器源码分析

本文深入探讨ARouter的拦截器实现机制,从逻辑分析、编译时期生成的辅助工具类、初始化时期的拦截器加载,到跳转时期如何进行拦截。分析了拦截器在编译时的生成,初始化时的加载,以及在路由跳转过程中的执行流程,揭示了拦截器执行顺序的关键点和超时处理策略。
摘要由CSDN通过智能技术生成

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) {
   
                    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值