ARouter V1.5.1 框架解析

ARouter是阿里開源的Android路由框架,主要用于解決Android應用組件化改造解耦后組件間跳轉(zhuǎn)、通信等操作。 本篇文章管中窺豹地簡單總結下ARouter的使用和源碼。

項目地址:
https://github.com/alibaba/ARouter

一、ARouter使用

1.1 框架引入

根工程build.gradle

dependencies {
   //ARouter插件依賴
   classpath "com.alibaba:arouter-register:1.0.2"
}

對需要路由的組件均做如下配置:build.gradle

plugins {
   //引入aroute插件
   id 'com.alibaba.arouter'
}

android {
   defaultConfig {
       //ARouter配置
       javaCompileOptions {
           annotationProcessorOptions {
               arguments = [AROUTER_MODULE_NAME: project.getName(), AROUTER_GENERATE_DOC: "enable"]
           }
       }
   }
}

dependencies {
   //arouter庫
   compileOnly("com.alibaba:arouter-api:1.5.0") {
   exclude group: 'com.android.support' //排除掉support包,保證版本統(tǒng)一
   }
   annotationProcessor("com.alibaba:arouter-compiler:1.2.2")
}

這里arouter庫一般只在宿主中通過implementation引入,各組件只需要compileOnly

1.2 使用

完整使用參考官方文檔。

這里以一個案例簡單介紹下常用的通過服務接口實現(xiàn)解耦組件間調(diào)用
案例組件構成:

  • host 宿主
  • base_core 基礎組件
  • ft_a 業(yè)務A組件
  • ft_login 業(yè)務登錄組件

業(yè)務A組件調(diào)用登錄組件登錄功能說明:

host:宿主

public class RefApplication extends Application {
    @Override
   public void onCreate() {
        super.onCreate();
       //ARouter初始化
       ARouter.init(this);
   }
}

application中做ARouter初始化

base_core組件:

定義接口

public interface LoginService extends IProvider {
   void login(Context context);
}

定義供外部組件統(tǒng)一調(diào)用的登錄功能包裝入口

public class LoginWrapper {
   private static LoginWrapper sLoginWrapper = null;
   @Autowired(name = Constants.LOGIN) // /login/login_service 至少兩級地址
   protected LoginService mLoginService;
   private LoginWrapper() {
       ARouter.getInstance().inject(this);
   }

   public static LoginWrapper getInstance() {
       if (sLoginWrapper == null) {
           synchronized (LoginWrapper.class) {
               if (sLoginWrapper == null) {
                   sLoginWrapper = new LoginWrapper();
               }
           }
       }
       return sLoginWrapper;
   }

   public void login(Context context) {
       mLoginService.login(context);
   }
}

ft_login組件

@Route(path = Constants.LOGIN)//與@Autowired name保持一致
public class LoginServiceImpl implements LoginService {

   @Override
   public void login(Context context) {
       //TODO login具體功能
   }

   @Override
   public void init(Context context) {
   //實現(xiàn)IProvider init()方法,這里就是個初始化回調(diào)
   }
}

ft_a組件

A組件調(diào)用登錄功能:

LoginWrapper.getInstance().login(this);

base_core業(yè)務組件都會依賴,以它作為中轉(zhuǎn)站,定義服務接口和提供具體服務執(zhí)行包裝類,不相互依賴的業(yè)務組件間通過它來統(tǒng)一獲取其他組件的功能。這里ft_a組件通過LoginWrapper調(diào)用login功能,內(nèi)部由接口LoginService通過注解的方式獲取ft_login具體實現(xiàn)LoginServiceImpl來執(zhí)行最終的login功能。下面通過這個流程來簡單看下ARouter內(nèi)部是怎么實現(xiàn)的。

二、ARouter源碼淺析

2.1 APT動態(tài)生成文件

ARouter在編譯階段通過APT動態(tài)生成一批文件:


這里Processor如何生成對應模板不鋪開分析了,這不是重點,感興趣的可以自行擼下源碼,這里簡單看下編譯生成的模板類是什么樣的:
@Router注解通過RouteProcessor生成存儲了path、group以及目標類相關映射關系的類文件:

public class ARouter$$Providers$$ft_login implements IProviderGroup {

 @Override
 public void loadInto(Map<String, RouteMeta> providers) {
 }
}

public class ARouter$$Root$$ft_login implements IRouteRoot {
  @Override
  public void loadInto(Map<String, Class<? extends IRouteGroup>> routes) {
    routes.put("login", ARouter$$Group$$login.class);
  }
}

public class ARouter$$Group$$login implements IRouteGroup {
  @Override
  public void loadInto(Map<String, RouteMeta> atlas) {
    atlas.put("/login/login_service", RouteMeta.build(RouteType.ACTIVITY, LoginActivity.class, "/login/login_service", "login", null, -1, -2147483648));
  }
}

@Autowired注解通過AutowiredProcessor也生成相關的映射文件

public class LoginWrapper$$ARouter$$Autowired implements ISyringe {
  private SerializationService serializationService;
  @Override
  public void inject(Object target) {
    serializationService = ARouter.getInstance().navigation(SerializationService.class);
   LoginWrapper substitute = (LoginWrapper)target;
   substitute.mLoginService = (LoginService)ARouter.getInstance().build("/login/login_service").navigation();
  }
}
2.2 ARouter初始化
ARouter.init(this)

這里ARouter作為門面,具體功能實現(xiàn)交由代理_ARouter來處理,整個init過程最終核心功能在LogisticsCenter.init(...)

public synchronized static void init(Context context, ThreadPoolExecutor tpe) throws HandlerException {
    mContext = context;
   executor = tpe;
   try {
        long startInit = System.currentTimeMillis();
       //billy.qi modified at 2017-12-06
       //load by plugin first
       loadRouterMap();
       if (registerByPlugin) {
            logger.info(TAG, "Load router map by arouter-auto-register plugin.");
       } else {
            Set<String> routerMap;
           // It will rebuild router map every times when debuggable.
           if (ARouter.debuggable() || PackageUtils.isNewVersion(context)) {
                logger.info(TAG, "Run with debug mode or new install, rebuild router map.");
               // These class was generated by arouter-compiler.
                //掃描com.alibaba.android.arouter.routes包下面包含的所有的ClassName
               routerMap = ClassUtils.getFileNameByPackageName(mContext, ROUTE_ROOT_PAKCAGE);
               if (!routerMap.isEmpty()) {
                    context.getSharedPreferences(AROUTER_SP_CACHE_KEY, Context.MODE_PRIVATE).edit().putStringSet(AROUTER_SP_KEY_MAP, routerMap).apply();
               }
                PackageUtils.updateVersion(context);    // Save new version name when router map update finishes.
           } else {
                logger.info(TAG, "Load router map from cache.");
               routerMap = new HashSet<>(context.getSharedPreferences(AROUTER_SP_CACHE_KEY, Context.MODE_PRIVATE).getStringSet(AROUTER_SP_KEY_MAP, new HashSet<String>()));
           }
            logger.info(TAG, "Find router map finished, map size = " + routerMap.size() + ", cost " + (System.currentTimeMillis() - startInit) + " ms.");
           startInit = System.currentTimeMillis();
           for (String className : routerMap) {
                //com.alibaba.android.arouter.routes.ARouter$$Root
                if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_ROOT)) {
                    // This one of root elements, load root.
                    //這里將該文件信息加載到Warehouse對應Map中,作為內(nèi)存緩存
                   ((IRouteRoot) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.groupsIndex);
                //com.alibaba.android.arouter.routes.ARouter$$Interceptors
               } else if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_INTERCEPTORS)) {
                    // Load interceptorMeta
                   ((IInterceptorGroup) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.interceptorsIndex);
                //com.alibaba.android.arouter.routes.ARouter$$Providers
               } else if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_PROVIDERS)) {
                    // Load providerIndex
                   ((IProviderGroup) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.providersIndex);
               }
            }
        }
...
}

init過程主要是掃描com.alibaba.android.arouter.routes包下動態(tài)生成的類,按映射關系(組分類、多級管理,按需初始化)分類加載到內(nèi)存,由Warehouse不同的Map來保存。

這里簡單看下RouteMeta的數(shù)據(jù)結構,以及其build方法

public class RouteMeta {
    private RouteType type;         // 路由支持的類型:ACTIVITY、SERVICE、PROVIDER、CONTENT_PROVIDER、BOARDCAST、METHOD、FRAGMENT、UNKNOWN
   private Element rawType;        // Raw type of route
   private Class<?> destination;   // 訪問的目標類
   private String path;            // 路由路徑,這里指Route注解設置的path
   private String group;           // Group of route 
   private int priority = -1;      // The smaller the number, the higher the priority
   private int extra;              // Extra data
   private Map<String, Integer> paramsType;  // Param type
   private String name;
   private Map<String, Autowired> injectConfig;  // Cache inject config.
   public RouteMeta() {
    }

    //初始化RouteMeta實例
   public static RouteMeta build(RouteType type, Class<?> destination, String path, String group, Map<String, Integer> paramsType, int priority, int extra) {
    return new RouteMeta(type, null, destination, null, path, group, paramsType, priority, extra);
}

然后將該實例添加到Map<String, RouteMeta> 中,key是Router path value是初始化好的RouteMeta實例。

2.3 路由的方式調(diào)用目標類的方法
LoginWrapper.getInstance().login(this);

從上面的源碼看,LoginWrapper作為包裝類,最終login方法是通過具體的service去實現(xiàn)。

那么這里就要了解如何發(fā)現(xiàn)化服務,官方介紹有兩種方式:

1) (推薦)使用依賴注入的方式發(fā)現(xiàn)服務,通過注解標注字段,即可使用,無需主動獲取
public class LoginWrapper {
   @Autowired(name = Constants.LOGIN)
    protected LoginService mLoginService;
   private LoginWrapper() {
        ARouter.getInstance().inject(this);
   }

    public void login(Context context) {
        mLoginService.login(context);
   }
}

為LoginService打上@Autowired注解,通過ARouter的inject方法直接調(diào)用APT生成的模板類:

inject方法的調(diào)用棧:

ARouter.inject ->_ARouter.inject -> AutowiredServiceImpl.autowire -> LoginWrapper$$ARouter$$Autowired.inject
public class LoginWrapper$$ARouter$$Autowired implements ISyringe {
  private SerializationService serializationService;
  @Override
  public void inject(Object target) {
    serializationService = ARouter.getInstance().navigation(SerializationService.class);
   LoginWrapper substitute = (LoginWrapper)target;
   substitute.mLoginService = (LoginService)ARouter.getInstance().build("/login/login_service").navigation();
  }
}
2)使用依賴查找的方式發(fā)現(xiàn)服務
public class LoginWrapper {
   protected LoginService mLoginService;
    public void login(Context context) {
        mLoginService = (LoginService) ARouter.getInstance().build(Constants.LOGIN).navigation();
       mLoginService.login(context);
   }
}

直接通過ARouter來查找,實現(xiàn)其實與APT生成的模板類是一樣的,只是從寫法上來說,打上@Autowired注解更簡潔,也是官方推薦的方式。

這里mLoginService最終實例對應的是ft_a中的LoginServiceImpl,通過它來實現(xiàn)具體的login功能。那么關鍵就是分析清楚如下代碼:

(LoginService) ARouter.getInstance().build(Constants.LOGIN).navigation();

從調(diào)用來看主要分兩步:

  • build("/login/login_service"):
_ARouter.java

protected Postcard build(String path) {
    if (TextUtils.isEmpty(path)) {
        throw new HandlerException(Consts.TAG + "Parameter is invalid!");
   } else {
        PathReplaceService pService = ARouter.getInstance().navigation(PathReplaceService.class);
       if (null != pService) {
            path = pService.forString(path);
       }
        //構建一個攜帶 path和group兩個路由地址數(shù)據(jù)的Postcard對象
        return build(path, extractGroup(path));
   }
}

整個build過程實際上就是構建一個Postcard。一個Postcard 對象就對應了一次路由請求,該對象作用于本次路由全過程。

  • navigation():

經(jīng)過層層調(diào)用最終核心實現(xiàn)在

com/alibaba/android/arouter/launcher/_ARouter.java

/**
* 參數(shù):
* Postcard this
* requestCode -1
* callback null
*/
protected Object navigation(final Context context, final Postcard postcard, final int requestCode, final NavigationCallback callback) {
   PretreatmentService pretreatmentService = ARouter.getInstance().navigation(PretreatmentService.class);
...
       //從Warehouse對應map中獲取@Router標記的目標類更多信息,完善當前Postcard
       LogisticsCenter.completion(postcard);
...

   //綠色通道,默認不走
   if (!postcard.isGreenChannel()) {   // It must be run in async thread, maybe interceptor cost too mush time made ANR.
...
   } else {
       return _navigation(context, postcard, requestCode, callback);
   }
   return null;
}

這里核心代碼就兩處:一個是通過LogisticsCenter.completion(postcard)來完善Postcard的類信息。另一個是通過_navigation來執(zhí)行對應的操作。

先看LogisticsCenter.completion()方法

public synchronized static void completion(Postcard postcard) {
    if (null == postcard) {
        throw new NoRouteFoundException(TAG + "No postcard!");
   }
   // 從倉庫的路由地址清單列表中嘗試獲取對應的RouteMeta
    RouteMeta routeMeta = Warehouse.routes.get(postcard.getPath());
   if (null == routeMeta) {    // Maybe its does't exist, or didn't load.
      // 如果前面沒獲取到,則根據(jù)一級地址,嘗試獲取對應的路由地址清單的文件類(ARouter$$Root$$工程名)
       Class<? extends IRouteGroup> groupMeta = Warehouse.groupsIndex.get(postcard.getGroup());  // 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();
               iGroupInstance.loadInto(Warehouse.routes);
               Warehouse.groupsIndex.remove(postcard.getGroup());
               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);   // Reload
       }
    } else {
      //完善postcard信息
       postcard.setDestination(routeMeta.getDestination());
       postcard.setType(routeMeta.getType());
       postcard.setPriority(routeMeta.getPriority());
       postcard.setExtra(routeMeta.getExtra());
       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 auto inject.
               postcard.getExtras().putStringArray(ARouter.AUTO_INJECT, paramsType.keySet().toArray(new String[]{}));
           }
            // Save raw uri
           postcard.withString(ARouter.RAW_URI, rawUri.toString());
       }
       //針對不同的type做不同的設置
       switch (routeMeta.getType()) {
           //如果是PROVIDER類型,會通過routeMeta獲取目標類,并實例化,最終由postcard.setProvider設置目標類的實例化對象
           case PROVIDER:  // if the route is provider, should find its instance
               // Its provider, so it must implement 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 {
                        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();    // Provider should skip all of interceptors
               break;
           case FRAGMENT:
                postcard.greenChannel();    // Fragment needn't interceptors
           default:
                break;
       }
    }
}

complete主要是通過Warehouse來完善postcard信息 ,這里因為LoginService繼承的IProvider,routeMeta對應的類型為PROVIDER,這里會初始化目標類LoginServiceImpl,并通過postcard.setProvider來設置到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:
            // Build intent
           final Intent intent = new Intent(currentContext, postcard.getDestination());
           intent.putExtras(postcard.getExtras());
           // Set flags.
           int flags = postcard.getFlags();
           if (-1 != flags) {
                intent.setFlags(flags);
           } else if (!(currentContext instanceof Activity)) {    // Non activity, need less one flag.
               intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
           }
            // Set Actions
           String action = postcard.getAction();
           if (!TextUtils.isEmpty(action)) {
                intent.setAction(action);
           }
            // Navigation in main looper.
           runInMainThread(new Runnable() {
                @Override
               public void run() {
                    startActivity(requestCode, currentContext, intent, postcard, callback);
               }
            });
           break;
       case PROVIDER:
            return postcard.getProvider();
       case BOARDCAST:
        case CONTENT_PROVIDER:
        case FRAGMENT:
            Class fragmentMeta = postcard.getDestination();
           try {
                Object instance = fragmentMeta.getConstructor().newInstance();
               if (instance instanceof Fragment) {
                    ((Fragment) instance).setArguments(postcard.getExtras());
               } else if (instance instanceof android.support.v4.app.Fragment) {
                    ((android.support.v4.app.Fragment) instance).setArguments(postcard.getExtras());
               }
                return instance;
           } catch (Exception ex) {
                logger.error(Consts.TAG, "Fetch fragment instance error, " + TextUtils.formatStackTrace(ex.getStackTrace()));
           }
        case METHOD:
        case SERVICE:
        default:
            return null;
   }
    return null;
}

根據(jù)PostCard攜帶的類型,做相應的操作。這里因為類型為PROVIDER,返回的 postcard.getProvider(),由上面complete我們知道postcard.getProvider()獲取的是目標類LoginServiceImpl的實例。

最后再總結一張ARoute核心工作原理圖:

本篇文章從組件化經(jīng)典應用案例出發(fā),通過分析涉及的框架源碼簡單了解了ARouter的核心工作原理, 僅僅只是管中窺豹,更詳細使用和說明還參考官方文檔。完成這篇文章又到了凌晨1點多,年前的最后一篇文章,希望新的一年能沉淀出更好的自己,加油!

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關閱讀更多精彩內(nèi)容

  • 前言 隨著項目業(yè)務邏輯和功能點日益遞增, 邏輯的耦合程度也逐漸升高, 組件化技術可以很好的解決這個問題, 公司大佬...
    SharryChoo閱讀 1,187評論 0 9
  • 目錄介紹 01.原生跳轉(zhuǎn)實現(xiàn) 02.實現(xiàn)組件跳轉(zhuǎn)方式2.1 傳統(tǒng)跳轉(zhuǎn)方式2.2 為何需要路由 03.ARouter...
    楊充211閱讀 2,127評論 0 16
  • 一、ARouter ARouter使用的是APT(Annotation Processing Tool)注解處理器...
    zzq_nene閱讀 2,445評論 0 0
  • 本來這期應該分享IoC思想和ARouter的自動注入這塊內(nèi)容,但是在自動注入這塊涉及到服務的主動注入,而我們前面只...
    juexingzhe閱讀 24,472評論 3 17
  • 久違的晴天,家長會。 家長大會開好到教室時,離放學已經(jīng)沒多少時間了。班主任說已經(jīng)安排了三個家長分享經(jīng)驗。 放學鈴聲...
    飄雪兒5閱讀 7,814評論 16 22

友情鏈接更多精彩內(nèi)容