ARouter源码解析

ARouter是阿里巴巴出品,帮助 Android App 进行组件化改造的路由框架,我们项目也使用的是ARouter路由框架进行解耦;
我打算分三部分进行解析ARouter框架:
第一部分:代码生成
第二部分:路由加载
第三部分:路由跳转

第一部分:代码生成

ARouter使用annotationProcessor配合JavaPoet进行代码生成;annotationProcessor顾名思义是注解处理器的意思。它对源代码文件进行检测找出其中的Annotation,根据注解自动生成代码。 Annotation处理器在处理Annotation时可以根据源文件中的Annotation生成额外的源文件和其它的文件,之后将编译生成的源文件和原来的源文件一起生成class文件。由于annotationProcessor不属于本篇范畴请点击这里查看详细用法。

《ARouter源码解析》 arouter-compiler.jpg

上图为ARouter annotationProcessor的代码;

AutowiredProcessor

AutowiredProcessor类的作用是根据Autowired注解的字段和这个注解字段的外围类来生成对应的类,生成的这个类命名方式为ClassName+\$$ARouter$$Autowired,并且实现接口implements ISyringepublic void inject(Object target)方法。ARouter.getInstance().inject(this);底层就调用的是这个inject方法。
如果上面这段文字很难理解请看下面源码解析一目了然:

注解类
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.CLASS)
public @interface Autowired {
    // Mark param's name or service name.
    //用来指定获取数据的名字,如果不设置直接用字段的名字获取数据
    String name() default "";
    // If required, app will be crash when value is null.
    // Primitive type wont be check!
    //true,如果被修饰的字段没有获取到数据会抛出异常
    boolean required() default false;
    // Description of the field
    //对这个字段进行解释,可以生成javadoc
    String desc() default "No desc.";
}
文件处理的入口方法
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        if (CollectionUtils.isNotEmpty(set)) {
            try {
                logger.info(">>> Found autowired field, start... <<<");
                //根据注解处理源码,生成Map<TypeElement, List<Element>>形式的map,
                // TypeElement为Autowired字段修饰的外围类,List<Element>为这个外围类中Autowired修饰的所有字段
              categories(roundEnvironment.getElementsAnnotatedWith(Autowired.class));
                //根据上个方法生成的结构来创建java类
                generateHelper();
            } catch (Exception e) {
                logger.error(e);
            }
            return true;
        }
        return false;
}
处理注解字段和外围类的方法
private void categories(Set<? extends Element> elements) throws IllegalAccessException {
        if (CollectionUtils.isNotEmpty(elements)) {
            for (Element element : elements) {
                //获取这个element的外围类
                TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

                if (element.getModifiers().contains(Modifier.PRIVATE)) {
                    throw new IllegalAccessException("The autowired fields CAN NOT BE 'private'!!! please check field ["
                            + element.getSimpleName() + "] in class [" + enclosingElement.getQualifiedName() + "]");
                }
                //判断外围类是否存在
                if (parentAndChild.containsKey(enclosingElement)) { // Has categries
                    //如果存在直接将Autowired注解修饰的字段添加到这个外围类中
                    parentAndChild.get(enclosingElement).add(element);
                } else {
                    //如果外围类不存在,创建
                    List<Element> childs = new ArrayList<>();
                    childs.add(element);
                    parentAndChild.put(enclosingElement, childs);
                }
            }
            logger.info("categories finished.");
        }
}
根据上面方法过滤出的结构创建文件的方法
private void generateHelper() throws IOException, IllegalAccessException {
        TypeElement type_ISyringe = elements.getTypeElement(ISYRINGE);
        TypeElement type_JsonService = elements.getTypeElement(JSON_SERVICE);
        TypeMirror iProvider = elements.getTypeElement(Consts.IPROVIDER).asType();
        TypeMirror activityTm = elements.getTypeElement(Consts.ACTIVITY).asType();
        TypeMirror fragmentTm = elements.getTypeElement(Consts.FRAGMENT).asType();
        TypeMirror fragmentTmV4 = elements.getTypeElement(Consts.FRAGMENT_V4).asType();
        // Build input param name.
        //方法参数为  (Object target)
        ParameterSpec objectParamSpec = ParameterSpec.builder(TypeName.OBJECT, "target").build();
        if (MapUtils.isNotEmpty(parentAndChild)) {
            for (Map.Entry<TypeElement, List<Element>> entry : parentAndChild.entrySet()) {
                // Build method : 'inject'
                /**
                 * 创建的方法为
                 * Override
                 * public void inject(Object target);
                 */
                MethodSpec.Builder injectMethodBuilder = MethodSpec.methodBuilder(METHOD_INJECT)
                        .addAnnotation(Override.class)
                        .addModifiers(PUBLIC)
                        .addParameter(objectParamSpec);
                //外围类
                TypeElement parent = entry.getKey();
                //所有注解的字段
                List<Element> childs = entry.getValue();
                //获取外围类包名加类的名字,例如:com.arouter.demo.Test1Activity
                String qualifiedName = parent.getQualifiedName().toString();
                //获取包名例如:com.arouter.demo
                String packageName = qualifiedName.substring(0, qualifiedName.lastIndexOf("."));
                //拼接生成类的名字Test1Activity$$ARouter$$Autowired
                String fileName = parent.getSimpleName() + NAME_OF_AUTOWIRED;
                logger.info(">>> Start process " + childs.size() + " field in " + parent.getSimpleName() + " ... <<<");
                //类的信息 javadoc  public class Test1Activity$$ARouter$$Autowired implements ISyringe
                TypeSpec.Builder helper = TypeSpec.classBuilder(fileName)
                        .addJavadoc(WARNING_TIPS)
                        .addSuperinterface(ClassName.get(type_ISyringe))
                        .addModifiers(PUBLIC);
                //创建字段   private SerializationService serializationService;
                FieldSpec jsonServiceField = FieldSpec.builder(TypeName.get(type_JsonService.asType()), "serializationService", Modifier.PRIVATE).build();
                helper.addField(jsonServiceField);
                /**
                 * 在方法体内创建赋值代码
                 * serializationService = ARouter.getInstance().navigation(ARouter.class);
                 * Test1Activity substitute = (Test1Activity)target;
                 */
                injectMethodBuilder.addStatement("serializationService = $T.getInstance().navigation($T.class);", ARouterClass, ClassName.get(type_JsonService));
                injectMethodBuilder.addStatement("$T substitute = ($T)target", ClassName.get(parent), ClassName.get(parent));
                // Generate method body, start inject.
                for (Element element : childs) {
                    Autowired fieldConfig = element.getAnnotation(Autowired.class);
                    String fieldName = element.getSimpleName().toString();
                    if (types.isSubtype(element.asType(), iProvider)) {  // It's provider
                        //如果继承IProvider
                        //判断Autowired是否写了name,如果写了就取name值获取数据,如果没写就用field字段本身的名字获取数据
                        if ("".equals(fieldConfig.name())) {    // User has not set service path, then use byType.
                            // Getter
                            //substitute.fieldName = ARouter.getInstance().navigation(ARouter.class);
                            injectMethodBuilder.addStatement(
                                    "substitute." + fieldName + " = $T.getInstance().navigation($T.class)",
                                    ARouterClass,
                                    ClassName.get(element.asType())
                            );
                        } else {    // use byName
                            // Getter
                            //substitute.fieldName = ARouter.getInstance().navigation(ARouter.class);
                            injectMethodBuilder.addStatement(
                                    "substitute." + fieldName + " = ($T)$T.getInstance().build($S).navigation();",
                                    ClassName.get(element.asType()),
                                    ARouterClass,
                                    fieldConfig.name()
                            );
                        }
                        // Validater
                        //如果Autowired中的required返回true,那么fieldName
                        if (fieldConfig.required()) {
                            injectMethodBuilder.beginControlFlow("if (substitute." + fieldName + " == null)");
                            injectMethodBuilder.addStatement(
                                    "throw new RuntimeException(\"The field '" + fieldName + "' is null, in class '\" + $T.class.getName() + \"!\")", ClassName.get(parent));
                            injectMethodBuilder.endControlFlow();
                        }
                    } else {    // It's normal intent value
                        String statment = "substitute." + fieldName + " = substitute.";
                        boolean isActivity = false;
                        if (types.isSubtype(parent.asType(), activityTm)) {  // Activity, then use getIntent()
                            isActivity = true;
                            statment += "getIntent().";
                        } else if (types.isSubtype(parent.asType(), fragmentTm) || types.isSubtype(parent.asType(), fragmentTmV4)) {   // Fragment, then use getArguments()
                            statment += "getArguments().";
                        } else {
                            throw new IllegalAccessException("The field [" + fieldName + "] need autowired from intent, its parent must be activity or fragment!");
                        }
                        /**
                         * 如上代码判断如果是activity就用getIntent()形式
                         * 如果是fragment就用getArguments()形式
                         * substitute.fieldName = substitute.getIntent().getStringExtra();  //如下1可以由多种形式,下面展示了两种形式
                         * serializationService.json2Object(substitute.getIntent().getStringExtra($S), $T.class)";
                         * if (null != serializationService){  //如2
                         *    substitute.fieldName = serializationService.json2Object(substitute.getIntent().getStringExtra($S), $T.class)";
                         * }else{
                         *    ARouter.e("ARouter::",You want automatic inject the field 'fieldName' in class 'Test1Activity' , then you should implement 'SerializationService' to support object auto inject!\")"
                         * }
                         */
                        statment = buildStatement(statment, typeUtils.typeExchange(element), isActivity); //1
                        if (statment.startsWith("serializationService.")) {   // Not mortals
                            injectMethodBuilder.beginControlFlow("if (null != serializationService)");   //2
                            injectMethodBuilder.addStatement(
                                    "substitute." + fieldName + " = " + statment,
                                    (StringUtils.isEmpty(fieldConfig.name()) ? fieldName : fieldConfig.name()),
                                    ClassName.get(element.asType())
                            );
                            injectMethodBuilder.nextControlFlow("else");
                            injectMethodBuilder.addStatement(
                                    "$T.e(\"" + Consts.TAG + "\", \"You want automatic inject the field '" + fieldName + "' in class '$T' , then you should implement 'SerializationService' to support object auto inject!\")", AndroidLog, ClassName.get(parent));
                            injectMethodBuilder.endControlFlow();
                        } else {
                            //substitute.fieldName = substitute.getIntent().getStringExtra();
                            injectMethodBuilder.addStatement(statment, StringUtils.isEmpty(fieldConfig.name()) ? fieldName : fieldConfig.name());
                        }

                        // Validator
                        //如果Autowired.required返回true,那么对这个字段进行强制校验,判断为null抛出异常
                        if (fieldConfig.required() && !element.asType().getKind().isPrimitive()) {  // Primitive wont be check.
                            injectMethodBuilder.beginControlFlow("if (null == substitute." + fieldName + ")");
                            injectMethodBuilder.addStatement(
                                    "$T.e(\"" + Consts.TAG + "\", \"The field '" + fieldName + "' is null, in class '\" + $T.class.getName() + \"!\")", AndroidLog, ClassName.get(parent));
                            injectMethodBuilder.endControlFlow();
                        }
                    }
                }
                helper.addMethod(injectMethodBuilder.build());
                // Generate autowire helper
                JavaFile.builder(packageName, helper.build()).build().writeTo(mFiler);
                logger.info(">>> " + parent.getSimpleName() + " has been processed, " + fileName + " has been generated. <<<");
            }
            logger.info(">>> Autowired processor stop. <<<");
        }
}
通过如下两段代码来看源文件和生成之后的文件

源文件

@Route(path = "/test/fragment")
public class BlankFragment extends Fragment {
    @Autowired
    String name;
    @Autowired(required = true)
    TestObj obj;
    public BlankFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        TextView textView = new TextView(getActivity());
        return textView;
    }
}

生成之后的文件

**
 * DO NOT EDIT THIS FILE!!! IT WAS GENERATED BY AROUTER. */
public class BlankFragment$$ARouter$$Autowired implements ISyringe {
  private SerializationService serializationService;
  @Override
  public void inject(Object target) {
    serializationService = ARouter.getInstance().navigation(SerializationService.class);;
    BlankFragment substitute = (BlankFragment)target;
    substitute.name = substitute.getArguments().getString("name");
    if (null != serializationService) {
      substitute.obj = serializationService.json2Object(substitute.getArguments().getString("obj"), TestObj.class);
    } else {
      Log.e("ARouter::", "You want automatic inject the field 'obj' in class 'BlankFragment' , then you should implement 'SerializationService' to support object auto inject!");
    }
    if (null == substitute.obj) {
      Log.e("ARouter::", "The field 'obj' is null, in class '" + BlankFragment.class.getName() + "!");
    }
  }
}

InterceptorProcessor

InterceptorProcessor类的作用是根据Interceptor注解的类来生成对应的类,生成的这个类命名方式为ARouter$$Interceptors$$moduleName其中moduleName为build.gradle中配置的,并且实现接口implements IInterceptorGrouppublic void loadInto(Map<Integer, Class<? extends IInterceptor>> interceptors)方法。在ARouter初始化的时候通过这个类的这个方法来获取所有的拦截器。

文件处理的入口方法
 @Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        if (CollectionUtils.isNotEmpty(annotations)) {
            //获取所有被Interceptor注解的element
            Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(Interceptor.class);
            try {
                //生成代码
                parseInterceptors(elements);
            } catch (Exception e) {
                logger.error(e);
            }
            return true;
        }
        return false;
}
根据Interceptor注解生成代码
private void parseInterceptors(Set<? extends Element> elements) throws IOException {
        if (CollectionUtils.isNotEmpty(elements)) {
            logger.info(">>> Found interceptors, size is " + elements.size() + " <<<");
            // Verify and cache, sort incidentally.
            for (Element element : elements) {
                //检查拦截器,必须实现IInterceptor接口并且使用Interceptor注解
                if (verify(element)) {  // Check the interceptor meta
                    logger.info("A interceptor verify over, its " + element.asType());
                    Interceptor interceptor = element.getAnnotation(Interceptor.class);
                    Element lastInterceptor = interceptors.get(interceptor.priority());
                    //不允许多个拦截器使用同一个优先级
                    if (null != lastInterceptor) { // Added, throw exceptions
                        throw new IllegalArgumentException(
                                String.format(Locale.getDefault(), "More than one interceptors use same priority [%d], They are [%s] and [%s].",
                                        interceptor.priority(),
                                        lastInterceptor.getSimpleName(),
                                        element.getSimpleName())
                        );
                    }
                    //根据优先级缓存
                    interceptors.put(interceptor.priority(), element);
                } else {
                    logger.error("A interceptor verify failed, its " + element.asType());
                }
            }
            // Interface of ARouter.
            TypeElement type_ITollgate = elementUtil.getTypeElement(IINTERCEPTOR);
            TypeElement type_ITollgateGroup = elementUtil.getTypeElement(IINTERCEPTOR_GROUP);
            /**
             *  Build input type, format as :
             *
             *  ```Map<Integer, Class<? extends ITollgate>>```
             */
            ParameterizedTypeName inputMapTypeOfTollgate = ParameterizedTypeName.get(
                    ClassName.get(Map.class),
                    ClassName.get(Integer.class),
                    ParameterizedTypeName.get(
                            ClassName.get(Class.class),
                            WildcardTypeName.subtypeOf(ClassName.get(type_ITollgate))
                    )
            );
            // Build input param name.
            //方法参数  (Map<Integer, Class<? extends IInterceptor>> interceptors)
            ParameterSpec tollgateParamSpec = ParameterSpec.builder(inputMapTypeOfTollgate, "interceptors").build();
            // Build method : 'loadInto'
            /**
             * 创建方法
             * Override
             * public void loadInto(Map<Integer, Class<? extends IInterceptor>> interceptors){}
             */
            MethodSpec.Builder loadIntoMethodOfTollgateBuilder = MethodSpec.methodBuilder(METHOD_LOAD_INTO)
                    .addAnnotation(Override.class)
                    .addModifiers(PUBLIC)
                    .addParameter(tollgateParamSpec);
            // Generate
            /**
             * 根据缓存生成代码
             * interceptors.put(priority,Test1Interceptor.class);
             */
            if (null != interceptors && interceptors.size() > 0) {
                // Build method body
                for (Map.Entry<Integer, Element> entry : interceptors.entrySet()) {
                    loadIntoMethodOfTollgateBuilder.addStatement("interceptors.put(" + entry.getKey() + ", $T.class)",
                            ClassName.get((TypeElement) entry.getValue()));
                }
            }
            // Write to disk(Write file even interceptors is empty.)
            /**
             * 生成类
             * moduleName为每个module的build.gradle里配置的
             * public class ARouter$$Interceptors$$moduleName implements IInterceptorGroup{
             *     public void loadInto(Map<Integer, Class<? extends IInterceptor>> interceprors){
             *         interceptors.put(priority,Test1Interceptor.class);
             *     }
             * }
             */
            JavaFile.builder(PACKAGE_OF_GENERATE_FILE,
                    TypeSpec.classBuilder(NAME_OF_INTERCEPTOR + SEPARATOR + moduleName)
                            .addModifiers(PUBLIC)
                            .addJavadoc(WARNING_TIPS)
                            .addMethod(loadIntoMethodOfTollgateBuilder.build())
                            .addSuperinterface(ClassName.get(type_ITollgateGroup))
                            .build()
            ).build().writeTo(mFiler);
            logger.info(">>> Interceptor group write over. <<<");
        }
}

源文件

@Interceptor(priority = 7)
public class Test1Interceptor implements IInterceptor {
    Context mContext;
    @Override
    public void process(final Postcard postcard, final InterceptorCallback callback) {

    }
    @Override
    public void init(Context context) {
    }
}

生成文件

public class ARouter$$Interceptors$$app implements IInterceptorGroup {
  @Override
  public void loadInto(Map<Integer, Class<? extends IInterceptor>> interceptors) {
    interceptors.put(7, Test1Interceptor.class);
  }
}

RouteProcessor

RouteProcessor类的作用是根据Route注解的类来生成对应的类,这个类是对应的路由表,也就是Group对应的path,path对应的类的Class。

文件处理的入口方法
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        if (CollectionUtils.isNotEmpty(annotations)) {
            //所有被Route注解的Element
            Set<? extends Element> routeElements = roundEnv.getElementsAnnotatedWith(Route.class);
            try {
                logger.info(">>> Found routes, start... <<<");
                //根据Element生成代码
                this.parseRoutes(routeElements);
            } catch (Exception e) {
                logger.error(e);
            }
            return true;
        }
        return false;
}
根据Route生成代码方法
private void parseRoutes(Set<? extends Element> routeElements) throws IOException {
        if (CollectionUtils.isNotEmpty(routeElements)) {
            // Perpare the type an so on.
            logger.info(">>> Found routes, size is " + routeElements.size() + " <<<");
            rootMap.clear();
            TypeMirror type_Activity = elements.getTypeElement(ACTIVITY).asType();
            TypeMirror type_Service = elements.getTypeElement(SERVICE).asType();
            TypeMirror fragmentTm = elements.getTypeElement(FRAGMENT).asType();
            TypeMirror fragmentTmV4 = elements.getTypeElement(Consts.FRAGMENT_V4).asType();

            // Interface of ARouter
            TypeElement type_IRouteGroup = elements.getTypeElement(IROUTE_GROUP);
            TypeElement type_IProviderGroup = elements.getTypeElement(IPROVIDER_GROUP);
            ClassName routeMetaCn = ClassName.get(RouteMeta.class);
            ClassName routeTypeCn = ClassName.get(RouteType.class);
            /*
               Build input type, format as :

               ```Map<String, Class<? extends IRouteGroup>>```
             */
            ParameterizedTypeName inputMapTypeOfRoot = ParameterizedTypeName.get(
                    ClassName.get(Map.class),
                    ClassName.get(String.class),
                    ParameterizedTypeName.get(
                            ClassName.get(Class.class),
                            WildcardTypeName.subtypeOf(ClassName.get(type_IRouteGroup))
                    )
            );
            /*

              ```Map<String, RouteMeta>```
             */
            ParameterizedTypeName inputMapTypeOfGroup = ParameterizedTypeName.get(
                    ClassName.get(Map.class),
                    ClassName.get(String.class),
                    ClassName.get(RouteMeta.class)
            );
            /*
              Build input param name.
              (Map<String, Class<? extends IRouteGroup>> routes)
             */
            ParameterSpec rootParamSpec = ParameterSpec.builder(inputMapTypeOfRoot, "routes").build();
            //(Map<String, RouteMeta> atlas)
            ParameterSpec groupParamSpec = ParameterSpec.builder(inputMapTypeOfGroup, "atlas").build();
            //(Map<String, RouteMeta> providers)
            ParameterSpec providerParamSpec = ParameterSpec.builder(inputMapTypeOfGroup, "providers").build();  // Ps. its param type same as groupParamSpec!
            /*
              Build method : 'loadInto'
              Override
              public void loadInto(Map<String, Class<? extends IRouteGroup>> routes);
             */
            MethodSpec.Builder loadIntoMethodOfRootBuilder = MethodSpec.methodBuilder(METHOD_LOAD_INTO)
                    .addAnnotation(Override.class)
                    .addModifiers(PUBLIC)
                    .addParameter(rootParamSpec);
            //  Follow a sequence, find out metas of group first, generate java file, then statistics them as root.
            for (Element element : routeElements) {
                TypeMirror tm = element.asType();
                Route route = element.getAnnotation(Route.class);
                RouteMeta routeMete = null;
                //如下代码组装RouterMete路由元数据
                if (types.isSubtype(tm, type_Activity)) {   // 1               // Activity
                    logger.info(">>> Found activity route: " + tm.toString() + " <<<");

                    // Get all fields annotation by @Autowired
                    Map<String, Integer> paramsType = new HashMap<>();
                    for (Element field : element.getEnclosedElements()) {
                        if (field.getKind().isField() && field.getAnnotation(Autowired.class) != null && !types.isSubtype(field.asType(), iProvider)) {
                            // It must be field, then it has annotation, but it not be provider.
                            //如果外围类是Activity,里面有被Autowired注解的字段且不是IProvider类型的,添加到Map中key为名字,value为字段类型的枚举值,具体查看typeUtils.typeExchange(field)方法
                            Autowired paramConfig = field.getAnnotation(Autowired.class);
                            paramsType.put(StringUtils.isEmpty(paramConfig.name()) ?
                                    field.getSimpleName().toString() : paramConfig.name(), typeUtils.typeExchange(field));
                        }
                    }
                    routeMete = new RouteMeta(route, element, RouteType.ACTIVITY, paramsType);
                } else if (types.isSubtype(tm, iProvider)) {         // IProvider
                    logger.info(">>> Found provider route: " + tm.toString() + " <<<");
                    routeMete = new RouteMeta(route, element, RouteType.PROVIDER, null);
                } else if (types.isSubtype(tm, type_Service)) {           // Service
                    logger.info(">>> Found service route: " + tm.toString() + " <<<");
                    routeMete = new RouteMeta(route, element, RouteType.parse(SERVICE), null);
                } else if (types.isSubtype(tm, fragmentTm) || types.isSubtype(tm, fragmentTmV4)) {
                    logger.info(">>> Found fragment route: " + tm.toString() + " <<<");
                    routeMete = new RouteMeta(route, element, RouteType.parse(FRAGMENT), null);
                }
                categories(routeMete);
                // if (StringUtils.isEmpty(moduleName)) {   // Hasn't generate the module name.
                //     moduleName = ModuleUtils.generateModuleName(element, logger);
                // }
            }
            /**
             * Override
             * public void loadInto(Map<String, RouteMeta> providers);
             */
            MethodSpec.Builder loadIntoMethodOfProviderBuilder = MethodSpec.methodBuilder(METHOD_LOAD_INTO)
                    .addAnnotation(Override.class)
                    .addModifiers(PUBLIC)
                    .addParameter(providerParamSpec);
            // Start generate java source, structure is divided into upper and lower levels, used for demand initialization.
            for (Map.Entry<String, Set<RouteMeta>> entry : groupMap.entrySet()) {
                String groupName = entry.getKey();
                /**
                 * Override
                 * public void loadInto(Map<String, RouteMeta> atlas);
                 */
                MethodSpec.Builder loadIntoMethodOfGroupBuilder = MethodSpec.methodBuilder(METHOD_LOAD_INTO)
                        .addAnnotation(Override.class)
                        .addModifiers(PUBLIC)
                        .addParameter(groupParamSpec);
                // Build group method body
                Set<RouteMeta> groupData = entry.getValue();
                for (RouteMeta routeMeta : groupData) {
                    switch (routeMeta.getType()) {
                        case PROVIDER:  // Need cache provider's super class
                            List<? extends TypeMirror> interfaces = ((TypeElement) routeMeta.getRawType()).getInterfaces();
                            /**
                             * 如下代码在方法public void loadInto(Map<String, RouteMeta> providers);中生成
                             * prvoiders.put("com.xxx.demo.HelloService",RouteMeta.build(RouteType.PROVIDER,HelloService.class,"/service/hello","service",null,priority,extra));
                             */
                            for (TypeMirror tm : interfaces) {
                                if (types.isSameType(tm, iProvider)) {   // Its implements iProvider interface himself.
                                    // This interface extend the IProvider, so it can be used for mark provider
                                    //tm 和 iProvider 相同
                                    loadIntoMethodOfProviderBuilder.addStatement(
                                            "providers.put($S, $T.build($T." + routeMeta.getType() + ", $T.class, $S, $S, null, " + routeMeta.getPriority() + ", " + routeMeta.getExtra() + "))",
                                            (routeMeta.getRawType()).toString(),
                                            routeMetaCn,
                                            routeTypeCn,
                                            ClassName.get((TypeElement) routeMeta.getRawType()),
                                            routeMeta.getPath(),
                                            routeMeta.getGroup());
                                } else if (types.isSubtype(tm, iProvider)) {
                                    // This interface extend the IProvider, so it can be used for mark provider
                                    // tm 是 iProvider 的子类
                                    loadIntoMethodOfProviderBuilder.addStatement(
                                            "providers.put($S, $T.build($T." + routeMeta.getType() + ", $T.class, $S, $S, null, " + routeMeta.getPriority() + ", " + routeMeta.getExtra() + "))",
                                            // tm.toString().substring(tm.toString().lastIndexOf(".") + 1),    // Spite unuseless name
                                            tm.toString(),    // So stupid, will duplicate only save class name.
                                            routeMetaCn,
                                            routeTypeCn,
                                            ClassName.get((TypeElement) routeMeta.getRawType()),
                                            routeMeta.getPath(),
                                            routeMeta.getGroup());
                                }
                            }
                            break;
                        default:
                            break;
                    }
                    // Make map body for paramsType
                    /**
                     * 如下代码只有Activity的时候才运行,查看上面 1
                     * 生成代码
                     * typeExchange,如上代码,为Autowired注解字段的类型
                     * put("Autowired.name",typeExchange);
                     */
                    StringBuilder mapBodyBuilder = new StringBuilder();
                    Map<String, Integer> paramsType = routeMeta.getParamsType();
                    if (MapUtils.isNotEmpty(paramsType)) {
                        for (Map.Entry<String, Integer> types : paramsType.entrySet()) {
                            mapBodyBuilder.append("put(\"").append(types.getKey()).append("\", ").append(types.getValue()).append("); ");
                        }
                    }
                    String mapBody = mapBodyBuilder.toString();
                    /**
                     * 如下代码在方法public void loadInto(Map<String, RouteMeta> atlas);中生成如下
                     * atlas.put("/service/hello",RouteMeta.build(RouteType.PROVIDER,HelloService.class,"/service/hello","service",null,priority,extra));
                     * 如果routeMeta.getType()为RouteType.ACTIVITY为下面这种形式
                     * atlas.put("/service/hello",RouteMeta.build(RouteType.PROVIDER,HelloService.class,"/service/hello","service",new java.util.HashMap<String, Integer>(){{put("Autowired.name",typeExchange);},priority,extra));
                     */
                    loadIntoMethodOfGroupBuilder.addStatement(
                            "atlas.put($S, $T.build($T." + routeMeta.getType() + ", $T.class, $S, $S, " + (StringUtils.isEmpty(mapBody) ? null : ("new java.util.HashMap<String, Integer>(){{" + mapBodyBuilder.toString() + "}}")) + ", " + routeMeta.getPriority() + ", " + routeMeta.getExtra() + "))",
                            routeMeta.getPath(),
                            routeMetaCn,
                            routeTypeCn,
                            ClassName.get((TypeElement) routeMeta.getRawType()),
                            routeMeta.getPath().toLowerCase(),
                            routeMeta.getGroup().toLowerCase());
                }
                // Generate groups
                /**
                 * 如下代码生成类
                 * package com.alibaba.android.arouter.routes;
                 * public class ARouter$$Group$$groupName implements IRouteGroup{
                 *     public void loadInto(Map<String, RouteMeta> atlas){
                 *          atlas.put("/service/hello",RouteMeta.build(RouteType.PROVIDER,HelloService.class,"/service/hello","service",null,priority,extra));
                 *          atlas.put("/service/hello",RouteMeta.build(RouteType.PROVIDER,HelloService.class,"/service/hello","service",new java.util.HashMap<String, Integer>(){{put("Autowired.name",typeExchange);},priority,extra));
                 *     }
                 * }
                 */
                String groupFileName = NAME_OF_GROUP + groupName;
                JavaFile.builder(PACKAGE_OF_GENERATE_FILE,
                        TypeSpec.classBuilder(groupFileName)
                                .addJavadoc(WARNING_TIPS)
                                .addSuperinterface(ClassName.get(type_IRouteGroup))
                                .addModifiers(PUBLIC)
                                .addMethod(loadIntoMethodOfGroupBuilder.build())
                                .build()
                ).build().writeTo(mFiler);
                logger.info(">>> Generated group: " + groupName + "<<<");
                rootMap.put(groupName, groupFileName);
            }
            /**
             * 如下方法是在
             * Override public void loadInto(Map<String, Class<? extends IRouteGroup>> routes);
             * 方法中创建如下代码
             * routes.put(groupName, ARouter$$Group$$groupName.class)
             */
            if (MapUtils.isNotEmpty(rootMap)) {
                // Generate root meta by group name, it must be generated before root, then I can findout the class of group.
                for (Map.Entry<String, String> entry : rootMap.entrySet()) {
                    loadIntoMethodOfRootBuilder.addStatement("routes.put($S, $T.class)", entry.getKey(), ClassName.get(PACKAGE_OF_GENERATE_FILE, entry.getValue()));
                }
            }
            // Wirte provider into disk
            /**
             * package com.alibaba.android.arouter.routes;
             * public class ARouter$$Providers$$moudleName implements IProviderGroup{
             *     public void loadInto(Map<String, RouteMeta> providers){
             *          prvoiders.put("com.xxx.demo.HelloService",RouteMeta.build(RouteType.PROVIDER,HelloService.class,"/service/hello","service",null,priority,extra));
             *     }
             * }
             */
            String providerMapFileName = NAME_OF_PROVIDER + SEPARATOR + moduleName;
            JavaFile.builder(PACKAGE_OF_GENERATE_FILE,
                    TypeSpec.classBuilder(providerMapFileName)
                            .addJavadoc(WARNING_TIPS)
                            .addSuperinterface(ClassName.get(type_IProviderGroup))
                            .addModifiers(PUBLIC)
                            .addMethod(loadIntoMethodOfProviderBuilder.build())
                            .build()
            ).build().writeTo(mFiler);
            logger.info(">>> Generated provider map, name is " + providerMapFileName + " <<<");
            // Write root meta into disk.
            /**
             * package com.alibaba.android.arouter.routes;
             * public class ARouter&&Root$$moduleName implements IRouteRoot{
             *      Override
             *      public void loadInto(Map<String, Class<? extends IRouteGroup>> routes){
             *          routes.put(groupName, ARouter$$Group$$groupName.class)
             *      }
             * }
             */
            String rootFileName = NAME_OF_ROOT + SEPARATOR + moduleName;
            JavaFile.builder(PACKAGE_OF_GENERATE_FILE,
                    TypeSpec.classBuilder(rootFileName)
                            .addJavadoc(WARNING_TIPS)
                           .addSuperinterface(ClassName.get(elements.getTypeElement(ITROUTE_ROOT)))
                            .addModifiers(PUBLIC)
                            .addMethod(loadIntoMethodOfRootBuilder.build())
                            .build()
            ).build().writeTo(mFiler);
            logger.info(">>> Generated root, name is " + rootFileName + " <<<");
        }
}

生成文件

public class ARouter$$Root$$app implements IRouteRoot {
  @Override
  public void loadInto(Map<String, Class<? extends IRouteGroup>> routes) {
    routes.put("service", ARouter$$Group$$service.class);
    routes.put("test", ARouter$$Group$$test.class);
  }
}
public class ARouter$$Group$$service implements IRouteGroup {
  @Override
  public void loadInto(Map<String, RouteMeta> atlas) {
    atlas.put("/service/hello", RouteMeta.build(RouteType.PROVIDER, HelloServiceImpl.class, "/service/hello", "service", null, -1, -2147483648));
    atlas.put("/service/json", RouteMeta.build(RouteType.PROVIDER, JsonServiceImpl.class, "/service/json", "service", null, -1, -2147483648));
    atlas.put("/service/single", RouteMeta.build(RouteType.PROVIDER, SingleService.class, "/service/single", "service", null, -1, -2147483648));
  }
}
总结:

上面对代码生成部分做了详细的代码注释,主要用到的技术就是annotationProcessor配合JavaPoet进行代码生成。

第二部分:路由加载

本地生成文件也进行编译打包,那么程序是如何找到这些路由加载到内存中呢,我们直接找到’LogisticsCenter.public synchronized static void init(Context context, ThreadPoolExecutor tpe)’方法

public synchronized static void init(Context context, ThreadPoolExecutor tpe) throws HandlerException {
        mContext = context;
        executor = tpe;
        try {
            // These class was generate by arouter-compiler.
            //在所有的dex中根据package包名获取arouter-compiler生成的class文件
            List<String> classFileNames = ClassUtils.getFileNameByPackageName(mContext, ROUTE_ROOT_PAKCAGE);

            //根据上面代码过滤出的class路径来讲Route加载到内存中
            for (String className : classFileNames) {
                if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_ROOT)) {
                    // This one of root elements, load root.
                    /**
                     * 获取arouter-compiler生成的ARouter$$Root$$moduleName类中的映射表
                     * 例如
                     * public class ARouter$$Root$$app implements IRouteRoot {
                     *   @Override
                     *   public void loadInto(Map<String, Class<? extends IRouteGroup>> routes) {
                     *     routes.put("service", ARouter$$Group$$service.class);
                     *     routes.put("test", ARouter$$Group$$test.class);
                     *   }
                     * }
                     */
                    ((IRouteRoot) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.groupsIndex);
                } else if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_INTERCEPTORS)) {
                    // Load interceptorMeta
                    /**
                     * 获取arouter-compiler生成的ARouter$$Interceptors$$moduleName类的映射表
                     * 例如
                     * public class ARouter$$Interceptors$$app implements IInterceptorGroup {
                     *   @Override
                     *   public void loadInto(Map<Integer, Class<? extends IInterceptor>> interceptors) {
                     *     interceptors.put(7, Test1Interceptor.class);
                     *   }
                     * }
                     */
                    ((IInterceptorGroup) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.interceptorsIndex);
                } else if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_PROVIDERS)) {
                    // Load providerIndex
                    /**
                     * 获取arouter-compiler生成的ARouter$$Providers$$moduleName类的映射表
                     * public class ARouter$$Providers$$app implements IProviderGroup {
                     *   @Override
                     *   public void loadInto(Map<String, RouteMeta> providers) {
                     *     providers.put("com.alibaba.android.arouter.demo.testservice.SingleService", RouteMeta.build(RouteType.PROVIDER, SingleService.class, "/service/single", "service", null, -1, -2147483648));
                     *   }
                     * }
                     */
                    ((IProviderGroup) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.providersIndex);
                }
            }
            if (Warehouse.groupsIndex.size() == 0) {
                logger.error(TAG, "No mapping files were found, check your configuration please!");
            }
            if (ARouter.debuggable()) {
                logger.debug(TAG, String.format(Locale.getDefault(), "LogisticsCenter has already been loaded, GroupIndex[%d], InterceptorIndex[%d], ProviderIndex[%d]", Warehouse.groupsIndex.size(), Warehouse.interceptorsIndex.size(), Warehouse.providersIndex.size()));
            }
        } catch (Exception e) {
            throw new HandlerException(TAG + "ARouter init logistics center exception! [" + e.getMessage() + "]");
        }
    }

在这个方法中难理解的地方是ClassUtils.getFileNameByPackageName(mContext, ROUTE_ROOT_PAKCAGE);方法,这个方法又调用List<String> getSourcePaths(Context context)方法,如下两个方法的代码注释:

/**
     * 通过指定包名,扫描包下面包含的所有的ClassName
     *
     * @param context     U know
     * @param packageName 包名
     * @return 所有class的集合
     */
    public static List<String> getFileNameByPackageName(Context context, String packageName) throws PackageManager.NameNotFoundException, IOException {
        List<String> classNames = new ArrayList<>();
        for (String path : getSourcePaths(context)) {
            DexFile dexfile = null;
            try {
                if (path.endsWith(EXTRACTED_SUFFIX)) {
                    //NOT use new DexFile(path), because it will throw "permission error in /data/dalvik-cache"
                    //提示权限错误 /data/dalvik-cache  这个目录
                    dexfile = DexFile.loadDex(path, path + ".tmp", 0);
                } else {
                    //虚拟机将在目录/data/dalvik-cache下生成对应的文件名字并打开它
                    dexfile = new DexFile(path);
                }
                Enumeration<String> dexEntries = dexfile.entries();
                while (dexEntries.hasMoreElements()) {
                    String className = dexEntries.nextElement();
                    if (className.contains(packageName)) {
                        classNames.add(className);
                    }
                }
            } catch (Throwable ignore) {
                Log.e("ARouter", "Scan map file in dex files made error.", ignore);
            } finally {
                if (null != dexfile) {
                    try {
                        dexfile.close();
                    } catch (Throwable ignore) {
                    }
                }
            }
        }
        Log.d("ARouter", "Filter " + classNames.size() + " classes by packageName <" + packageName + ">");
        return classNames;
    }

List<String> getSourcePaths(Context context)方法

public static List<String> getSourcePaths(Context context) throws PackageManager.NameNotFoundException, IOException {
        ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
        File sourceApk = new File(applicationInfo.sourceDir);
//        Log.e(TAG,sourceApk.getAbsolutePath());
//        Log.e(TAG,"12121212 : " + applicationInfo.sourceDir);
        logger.info(TAG,"12121212 : " + applicationInfo.sourceDir);
        List<String> sourcePaths = new ArrayList<>();
        sourcePaths.add(applicationInfo.sourceDir); //add the default apk path
        //the prefix of extracted file, ie: test.classes
        String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT;
        Log.e(TAG,extractedFilePrefix);
//        如果VM已经支持了MultiDex,就不要去Secondary Folder加载 Classesx.zip了,那里已经么有了
//        通过是否存在sp中的multidex.version是不准确的,因为从低版本升级上来的用户,是包含这个sp配置的
        /**
         * 如下这个方法判断虚拟机是否支持multidex,java.vm.version大于2.1的就是art虚拟机默认支持multidex
         * 如果虚拟机为art默认支持multidex那么dex的路径只有一个那就是applicationInfo.sourceDir例如: /data/app/com.alibaba.android.arouter.demo-wqT7WUHrcYy8UDBDFIXTmg==/base.apk
         * 如果虚拟机为dalvik默认不支持multidex,且对dex进行分包处理那么加载/data/data/com.alibaba.android.arouter.demo/code_cache/secondray-dexes/
         * 如果虚拟机为dalvik默认不支持multidex,且由于代码量太少没有进行分包处理那么加载applicationInfo.sourceDir路径
         */
        if (!isVMMultidexCapable()) {
            //the total dex numbers
            int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1);
            File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME);
            //扫描/data/data/com.alibaba.android.arouter.demo/code_cache/secondray-dexes/  路径下所有的  xxx.apk.classes2.zip
            for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) {
                //扫描/data/data/com.alibaba.android.arouter.demo/code_cache/secondray-dexes/ for each dex file, ie: test.classes2.zip, test.classes3.zip...
                String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX;
                File extractedFile = new File(dexDir, fileName);
                if (extractedFile.isFile()) {
                    sourcePaths.add(extractedFile.getAbsolutePath());
                    //we ignore the verify zip part
                } else {
                    throw new IOException("Missing extracted secondary dex file '" + extractedFile.getPath() + "'");
                }
            }
        }
        if (ARouter.debuggable()) { // Search instant run support only debuggable
            sourcePaths.addAll(tryLoadInstantRunDexFile(applicationInfo));
        }
        return sourcePaths;
}

经过’public synchronized static void init(Context context, ThreadPoolExecutor tpe) throws HandlerException’方法之后将arouter-compiler生成的代码加载到内存中提供程序使用,如下类:

class Warehouse {
    // Cache route and metas
    //加载ARouter$$Root$$moduleName类的映射表
    static Map<String, Class<? extends IRouteGroup>> groupsIndex = new HashMap<>();
    static Map<String, RouteMeta> routes = new HashMap<>();
    // Cache provider
    static Map<Class, IProvider> providers = new HashMap<>();
    //加载ARouter$$Providers$$moduleName类的映射表
    static Map<String, RouteMeta> providersIndex = new HashMap<>();
    // Cache interceptor
    //加载ARouter$$Interceptors$$moduleName类的映射表
    static Map<Integer, Class<? extends IInterceptor>> interceptorsIndex = new UniqueKeyTreeMap<>("More than one interceptors use same priority [%s]");
    static List<IInterceptor> interceptors = new ArrayList<>();
}

如下两张图片图一为art虚拟机编译后获取dex文件的目录,图二为dalvik虚拟机编译后获取dex文件的目录

《ARouter源码解析》 art.jpg

《ARouter源码解析》 dalvik_multidex.jpg

总结:

根据虚拟机是否默认支持multidex,分别在不同的文件夹中扫描生成的zip或apk文件路径;将路径通过DexFile获取所有的className,通过指定的package来过滤出有用的className;在将过滤出来的className填充到Warehouse类中的缓存中,给程序提供使用。

第一部分:路由跳转

路由跳转方法调用栈

//ARouter类
ARouter.getInstance().build(BaseConstantDef.ROUTER_PATH_AC1).navigation();
//_ARouter类
protected Object navigation(final Context context, final Postcard postcard, final int requestCode, final NavigationCallback callback);
//如上方法中调用
LogisticsCenter.completion(postcard);//拼装Postcard类
//符合要求执行拦截器
interceptorService.doInterceptions();
//最后调用真正的跳转方法
private Object _navigation(final Context context, final Postcard postcard, final int requestCode, final NavigationCallback callback)

上面是路由跳转的方法调用栈,下面是代码解析:
LogisticsCenter.completion(postcard)方法

public synchronized static void completion(Postcard postcard) {
        if (null == postcard) {
            throw new NoRouteFoundException(TAG + "No postcard!");
        }
        /**
         * 这部分代码
         * 1. path在Warehouse.routes缓存中没有,进入这个分支
         * 2. 根据group在Warehouse.groupsIndex中取出对应的IRouterGroup这个接口中存放的就是这个group中所有的path
         * 3. 取出之后将这个group下的所有path缓存到Warehouse.routes中,key为path,value为RouteMeta
         * 4. 缓存成功删除Warehouse.groupsIndex中对应的group数据
         * 5. 重复调用completion方法,根据path命中缓存取出RouteMeta
         * 6. 根据RouteMeta来组装Postcard
         * 7. 解析Uri中的参数,拼装成Android的bundle传输
         * 8. routeMeta.getType()如果等于provider,那么从Warehouse.providers中根据routeMeta.getDestination()取出Provider
         * 9. 如果取出为空那么创建,并且缓存到Warehouse.providers中,key为provider的class,value为provider的实例对象
         * 10. 如果是provider 设置postcard.greenChannel() 跳过拦截器
         * 11. 从第8点开始 routeMeta.getType()如果等于fragment,则直接设置postcard.greenChannel() 跳过拦截器
         */
        RouteMeta routeMeta = Warehouse.routes.get(postcard.getPath());   //  1
        if (null == routeMeta) {    // Maybe its does't exist, or didn't load.
            Class<? extends IRouteGroup> groupMeta = Warehouse.groupsIndex.get(postcard.getGroup());  // 2 Load route meta.
            if (null == groupMeta) {
                throw new NoRouteFoundException(TAG + "There is no route match the path [" + postcard.getPath() + "], in group [" + postcard.getGroup() + "]");
            } else {
                // Load route and cache it into memory, then delete from metas.
                try {
                    if (ARouter.debuggable()) {
                        logger.debug(TAG, String.format(Locale.getDefault(), "The group [%s] starts loading, trigger by [%s]", postcard.getGroup(), postcard.getPath()));
                    }
                    IRouteGroup iGroupInstance = groupMeta.getConstructor().newInstance();   // 3
                    iGroupInstance.loadInto(Warehouse.routes);
                    Warehouse.groupsIndex.remove(postcard.getGroup());  //  4
                    if (ARouter.debuggable()) {
                        logger.debug(TAG, String.format(Locale.getDefault(), "The group [%s] has already been loaded, trigger by [%s]", postcard.getGroup(), postcard.getPath()));
                    }
                } catch (Exception e) {
                    throw new HandlerException(TAG + "Fatal exception when loading group meta. [" + e.getMessage() + "]");
                }
                completion(postcard);   // 5  Reload
            }
        } else {
            // 6
            postcard.setDestination(routeMeta.getDestination());
            postcard.setType(routeMeta.getType());
            postcard.setPriority(routeMeta.getPriority());
            postcard.setExtra(routeMeta.getExtra());
            //  7
            Uri rawUri = postcard.getUri();
            if (null != rawUri) {   // Try to set params into bundle.
                Map<String, String> resultMap = TextUtils.splitQueryParameters(rawUri);
                Map<String, Integer> paramsType = routeMeta.getParamsType();

                if (MapUtils.isNotEmpty(paramsType)) {
                    // Set value by its type, just for params which annotation by @Param
                    for (Map.Entry<String, Integer> params : paramsType.entrySet()) {
                        setValue(postcard,
                                params.getValue(),
                                params.getKey(),
                                resultMap.get(params.getKey()));
                    }
                    // Save params name which need autoinject.
                    postcard.getExtras().putStringArray(ARouter.AUTO_INJECT, paramsType.keySet().toArray(new String[]{}));
                }
                // Save raw uri
                postcard.withString(ARouter.RAW_URI, rawUri.toString());
            }
            switch (routeMeta.getType()) {
                case PROVIDER:  // 8  if the route is provider, should find its instance
                    // Its provider, so it must be implememt IProvider
                    Class<? extends IProvider> providerMeta = (Class<? extends IProvider>) routeMeta.getDestination();
                    IProvider instance = Warehouse.providers.get(providerMeta);
                    if (null == instance) { // There's no instance of this provider
                        IProvider provider;
                        try {
                            // 9
                            provider = providerMeta.getConstructor().newInstance();
                            provider.init(mContext);
                            Warehouse.providers.put(providerMeta, provider);
                            instance = provider;
                        } catch (Exception e) {
                            throw new HandlerException("Init provider failed! " + e.getMessage());
                        }
                    }
                    postcard.setProvider(instance);
                    postcard.greenChannel();   // 10  Provider should skip all of interceptors
                    break;
                case FRAGMENT:
                    postcard.greenChannel();    // Fragment needn't interceptors
                default:
                    break;
            }
        }
}

interceptorService.doInterceptions()拦截器查看InterceptorServiceImpl源码:

@Override
public void doInterceptions(final Postcard postcard, final InterceptorCallback callback) {
        if (null != Warehouse.interceptors && Warehouse.interceptors.size() > 0) {
            checkInterceptorsInitStatus();
            if (!interceptorHasInit) {
                callback.onInterrupt(new HandlerException("Interceptors initialization takes too much time."));
                return;
            }
            LogisticsCenter.executor.execute(new Runnable() {
                @Override
                public void run() {
                    //这个同步工具类是为了防止在拦截器中不回掉callback方法,或者拦截器中有线程延迟回调callback方法
                    CancelableCountDownLatch interceptorCounter = new CancelableCountDownLatch(Warehouse.interceptors.size());
                    try {
                        //递归执行所有拦截器
                        _excute(0, interceptorCounter, postcard);
                        //这段代码是等待拦截器中线程执行完成回调callback来清除CountDownLatch标志,但是他有个超时时间
                        interceptorCounter.await(postcard.getTimeout(), TimeUnit.SECONDS);
                        if (interceptorCounter.getCount() > 0) {    // Cancel the navigation this time, if it hasn't return anythings.
                            callback.onInterrupt(new HandlerException("The interceptor processing timed out."));
                        } else if (null != postcard.getTag()) {    // Maybe some exception in the tag.
                            callback.onInterrupt(new HandlerException(postcard.getTag().toString()));
                        } else {
                            callback.onContinue(postcard);
                        }
                    } catch (Exception e) {
                        callback.onInterrupt(e);
                    }
                }
            });
        } else {
            callback.onContinue(postcard);
        }
}

protected Object navigation(final Context context, final Postcard postcard, final int requestCode, final NavigationCallback callback)

protected Object navigation(final Context context, final Postcard postcard, final int requestCode, final NavigationCallback callback) {
        try {
            //拼装Postcard类
            LogisticsCenter.completion(postcard);
        } catch (NoRouteFoundException ex) {
            logger.warning(Consts.TAG, ex.getMessage());

            if (debuggable()) { // Show friendly tips for user.
                Toast.makeText(mContext, "There's no route matched!\n" +
                        " Path = [" + postcard.getPath() + "]\n" +
                        " Group = [" + postcard.getGroup() + "]", Toast.LENGTH_LONG).show();
            }
            if (null != callback) {
                callback.onLost(postcard);
            } else {    // No callback for this invoke, then we use the global degrade service.
                DegradeService degradeService = ARouter.getInstance().navigation(DegradeService.class);
                if (null != degradeService) {
                    degradeService.onLost(context, postcard);
                }
            }
            return null;
        }
        if (null != callback) {
            callback.onFound(postcard);
        }
        if (!postcard.isGreenChannel()) {   // It must be run in async thread, maybe interceptor cost too mush time made ANR.
            /**
             *除了provider和fragment都需要走拦截器,然后在发送navigation
             * 请查看InterceptorServiceImpl源码异步执行所有拦截器,并且通过CountDownLatch来进行同步
             */
            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);
        }
        return null;
}

参考文献:
http://www.importnew.com/15731.html
https://it.baiked.com/jdkapi1.8/javax/lang/model/element/TypeElement.html

    原文作者:码农一颗颗
    原文地址: https://www.jianshu.com/p/cdf2649d2bc3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞