Android开发经验谈Android技术知识Android进阶之路

ARouter源码分析(1)-基本路由流程

2018-10-19  本文已影响15人  susion哒哒

前面作者分析了一遍WMRouter的源代码,趁着思路比较活跃,就打算把ARouter的源码也看一下,然后对这两个路由方案做一个对比。

文章是作者学习ARouter的源码的重点纪要。 ARouter官方文档 : https://github.com/alibaba/ARouter/blob/master/README_CN.md

先通过一张图来了解ARouter的路由过程以及相关类:

ARouter路由流程.png

本文先不对路由表的生成做详细了解,也不对InterceptorServiceGlobalDegradeService的加载做仔细分析,我们就先根据源码来大致看一遍路由的基本过程。

基本路由流程

ARouter中如果使用一个 @Route(path = "/test/activity1")注解标注在了一个Activity上,那么这个Activity就是可被路由的。我们可以通过调用下面代码实现页面跳转:

    ARouter.getInstance()
                .build("/test/activity1")
                .navigation(context, new NavigationCallback());

ARouter只是一个门面类,实际功能的实现是由_ARouter完成的。来看一下_ARouter.navigation()方法。注意为了只看主流程,我删去了一些逻辑

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

            if (null != callback) {
                callback.onLost(postcard); //页面降级
            } else {   
                DegradeService degradeService = ARouter.getInstance().navigation(DegradeService.class);
                degradeService.onLost(context, postcard); //全局降级
            }
            return null;
        }

        if (null != callback) callback.onFound(postcard);

        //新开线程,异步执行拦截器
        interceptorService.doInterceptions(postcard, new InterceptorCallback() {
    
            @Override public void onContinue(Postcard postcard) {
                _navigation(context, postcard, requestCode, callback);
            }

            @Override public void onInterrupt(Throwable exception) {
                callback.onInterrupt(postcard);
            }
        });
        return null;
    }

LogisticsCenter 装配 Postcard

    public synchronized static void completion(Postcard postcard) {
        //从路由表中获取该路由的RouteMeta
        RouteMeta routeMeta = Warehouse.routes.get(postcard.getPath());

        if (null == routeMeta) {   //路由表中不存在就尝试加载
            Class<? extends IRouteGroup> groupMeta = Warehouse.groupsIndex.get(postcard.getGroup());  // 首先把这次路由对应的路由组的表加载出来
            if (null == groupMeta) {
                throw new NoRouteFoundException(TAG + "There is no route match the path [" + postcard.getPath() + "], in group [" + postcard.getGroup() + "]");
            } else {
                try {
                    IRouteGroup iGroupInstance = groupMeta.getConstructor().newInstance();
                    iGroupInstance.loadInto(Warehouse.routes);
                    Warehouse.groupsIndex.remove(postcard.getGroup());
                } catch (Exception e) {
                    throw new HandlerException(TAG + "Fatal exception when loading group meta. [" + e.getMessage() + "]");
                }
                completion(postcard);   // Reload
            }
        } else {
            //把对用的RouteMeta信息设置到Postcard中
            postcard.setDestination(routeMeta.getDestination()); // destination这里就是Activity类对象
            postcard.setType(routeMeta.getType());
            ....
            postcard.withString(ARouter.RAW_URI, postcard.getUri().toString());
            ...
        }
    }

来总结一下这个方法的主要流程:

  1. 尝试从路由表Warehouse.routes获取postcard.getPath()对应的路由信息。
  2. 如果不存在RouteMeta,则加载postcard.getPath()对应的路由组表Warehouse.groupsIndex。如果根本不存在对应的组,则路由失败
  3. 实例化Warehouse.groupsIndex, 然后把表内的信息加载到Warehouse.routes表中,再次调用completion()
  4. 获取到postcard.getPath()对应的RouteMeta,使用RouteMeta完善Postcard

我们先来看一眼如何把Warehouse.groupsIndex的信息加载到Warehouse.routes中:

这其实IRouteGroup接口的实例是动态生成的:

public class ARouter$$Group$$test implements IRouteGroup {
  @Override
  public void loadInto(Map<String, RouteMeta> atlas) {
    atlas.put("/test/activity1", RouteMeta.build(RouteType.ACTIVITY, Test1Activity.class, "/test/activity1", "test", -1, -2147483648));
    atlas.put("/test/activity2", RouteMeta.build(RouteType.ACTIVITY, Test2Activity.class, "/test/activity2", "test", -1, -2147483648));
  }
}

loadInto()实际上是把路由信息放入到Warehouse.routes中。

浅尝辄止,我们继续往下看,这里我们直接看拦截器实例:

拦截器

@Route(path = "/arouter/service/interceptor") 
public class InterceptorServiceImpl implements InterceptorService {

    @Override
    public void doInterceptions(final Postcard postcard, final InterceptorCallback callback) {
        if (null != Warehouse.interceptors && Warehouse.interceptors.size() > 0) {
            ..确保拦截器初始化完毕
            LogisticsCenter.executor.execute(new Runnable() {
                @Override
                public void run() {
                    //依次执行每一个拦截器
                    _excute(0, interceptorCounter, postcard);
                }
            });
        } else {
            callback.onContinue(postcard);
        }
    }
}

@Route(path = "/arouter/service/interceptor")标注,其实这个拦截器会在运行时动态加载。可以看到大致逻辑就是:

在异步线程中依次执行每一个拦截器。其实在这里可以看出ARouter的拦截器是全局的,即每一次路由如果不设置不被拦截的标志,则都会把拦截器走一遍。

在Postcard组装完毕和拦截器执行完毕后,就会调用_navigation()

private Object _navigation(final Context context, final Postcard postcard, final int requestCode, final NavigationCallback callback) {
        final Context currentContext = null == context ? mContext : context;
        switch (postcard.getType()) {
            case ACTIVITY:
                // intent中设置一些信息。

                // Navigation in main looper.
                runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        startActivity(requestCode, currentContext, intent, postcard, callback);
                    }
                });
                break;
            case ...
        }
        return null;
    }

到这里,一次Activity的路由算是完成了。不过这其中我们还有很多细节没有仔细讨论:1

  1. Warehouse.routes路由表和Warehouse.groupsIndex路由组表是如何加载的
  2. InterceptorServiceDegradeService 是如何加载的
  3. ARouter是支持在运行时期获取不在同一个库的类实例的,比如Fragment,这是怎么实现的呢?
  4. ..

这些点,我们在后续文章再继续分析。

上一篇下一篇

猜你喜欢

热点阅读