1-初始化
ARouter.init()開始,init方法的主要工作就是ARouter實例化乾颁,_ARouter的初始化缓呛。_ARouter是具體實現(xiàn)類。這里用到了外觀模式靠欢,將所有API通過ARouter暴露廊敌,具體實現(xiàn)則交由_ARouter
//ARouter.java
public static void init(Application application) {
if (!hasInit) {
//日志類
logger = _ARouter.logger;
_ARouter.logger.info(Consts.TAG, "ARouter init start.");
//@1._ARouter初始化
hasInit = _ARouter.init(application);
if (hasInit) {
//@4.通過路由開啟Service,預解析攔截器
_ARouter.afterInit();
}
_ARouter.logger.info(Consts.TAG, "ARouter init over.");
}
}
@1._ARouter的初始化:
protected static synchronized boolean init(Application application) {
mContext = application;
//@2.LogisticsCenter初始化
LogisticsCenter.init(mContext, executor);
logger.info(Consts.TAG, "ARouter init success!");
hasInit = true;
//主線程Looper創(chuàng)建一個Handler
mHandler = new Handler(Looper.getMainLooper());
return true;
}
@2.LogisticsCenter初始化门怪。主要工作就是初始化所有類的map骡澈。在編譯期通過gradle插件(arouter-compiler)掃描文件,生成路由映射文件掷空,apt生成路由映射關系文件肋殴。
public synchronized static void init(Context context, ThreadPoolExecutor tpe) throws HandlerException {
mContext = context;
executor = tpe;
try {
。坦弟。护锤。
if (registerByPlugin) {
。酿傍。烙懦。
} else {
Set<String> routerMap;
//debuggable模式或版本更新,重新獲取routerMap映射表
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.
//遍歷arouter-compiler生成的包名下所有文件赤炒,讀取routerMap路由映射表氯析,將routerMap存儲在sp中
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 {
//直接從sp中讀取routerMap亏较。set<String>類型,存儲的是className
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();
//@3.遍歷routerMap掩缓,根據(jù)文件類型存儲到Warehouse對應的字段宴杀。通過反射實例化對象,調(diào)用loadInto實現(xiàn)拾因。
for (String className : routerMap) {
if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_ROOT)) {
// This one of root elements, load root.
((IRouteRoot) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.groupsIndex);
} else if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_INTERCEPTORS)) {
// Load interceptorMeta
((IInterceptorGroup) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.interceptorsIndex);
} else if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_PROVIDERS)) {
// Load providerIndex
((IProviderGroup) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.providersIndex);
}
}
}
logger.info(TAG, "Load root element finished, cost " + (System.currentTimeMillis() - startInit) + " ms.");
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() + "]");
}
}
@3.這里存儲到Warehose里的主要是三個HashMap旺罢,分別是groupsIndex、interceptorsIndex绢记、providersIndex
- interceptorsIndex-TreeMap實現(xiàn)扁达,根據(jù)攔截器的優(yōu)先級自平衡的有序結構,紅黑樹實現(xiàn)蠢熄。key是優(yōu)先級跪解,value是攔截器類名
- groupsIndex-key是路由的group,value是該group下的路由映射關系類
- providersIndex-
存儲過程是通過routerMap拿到className签孔,反射生成實例調(diào)用其loadInto方法叉讥,該方法是APT在@Route注解的類中自動生成的代碼
public class ARouter$$Root$$app implements IRouteRoot {
@Override
public void loadInto(Map<String, Class<? extends IRouteGroup>> routes) {
//key為分組名,即路徑的第一段饥追,value為分組中所有的映射關系
routes.put("service", ARouter$$Group$$service.class);
routes.put("test", ARouter$$Group$$test.class);
}
}
//將module中使用@Route注解的activity或Fragment添加到集合中图仓,這里的方法會在之后調(diào)用
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", new java.util.HashMap<String, Integer>(){{put("pac", 9); put("ch", 5); put("fl", 6); put("obj", 10); put("name", 8); put("dou", 7); put("boy", 0); put("objList", 10); put("map", 10); put("age", 3); put("url", 8); put("height", 3); }}, -1, -2147483648));
atlas.put("/test/activity2", RouteMeta.build(RouteType.ACTIVITY, Test2Activity.class, "/test/activity2", "test", new java.util.HashMap<String, Integer>(){{put("key1", 8); }}, -1, -2147483648));
atlas.put("/test/activity3", RouteMeta.build(RouteType.ACTIVITY, Test3Activity.class, "/test/activity3", "test", new java.util.HashMap<String, Integer>(){{put("name", 8); put("boy", 0); put("age", 3); }}, -1, -2147483648));
atlas.put("/test/activity4", RouteMeta.build(RouteType.ACTIVITY, Test4Activity.class, "/test/activity4", "test", null, -1, -2147483648));
atlas.put("/test/fragment", RouteMeta.build(RouteType.FRAGMENT, BlankFragment.class, "/test/fragment", "test", null, -1, -2147483648));
atlas.put("/test/webview", RouteMeta.build(RouteType.ACTIVITY, TestWebview.class, "/test/webview", "test", null, -1, -2147483648));
}
}
@4._ARouter.afterInit()方法。通過ARouter獲取管理攔截器的Service的實例但绕,并開啟服務進行攔截器的一些初始化工作救崔。
static void afterInit() {
// Trigger interceptor init, use byName.
interceptorService = (InterceptorService) ARouter.getInstance().build("/arouter/service/interceptor").navigation();
}
InterceptorServiceImpl服務主要是實例化攔截器,并將實例添加到Warehose的interceptors中
@Route(path = "/arouter/service/interceptor")
public class InterceptorServiceImpl implements InterceptorService {
private static boolean interceptorHasInit;
private static final Object interceptorInitLock = new Object();
@Override
public void init(final Context context) {
... //省略子線程以及同步處理捏顺,下面的操作實際是在子線程處理的
if (MapUtils.isNotEmpty(Warehouse.interceptorsIndex)) {
for (Map.Entry<Integer, Class<? extends IInterceptor>> entry : Warehouse.interceptorsIndex.entrySet()) {
Class<? extends IInterceptor> interceptorClass = entry.getValue();
try {
IInterceptor iInterceptor = interceptorClass.getConstructor().newInstance();
iInterceptor.init(context);
Warehouse.interceptors.add(iInterceptor);
} catch (Exception ex) {
throw new HandlerException(TAG + "ARouter init interceptor error! name = [" + interceptorClass.getName() + "], reason = [" + ex.getMessage() + "]");
}
}
...
}
}
總結初始化過程:
- (1)ARouter.init()-->_ARouter.init()-->LogisticsCenter.init()
- (2)debuggable()模式或新版本六孵,則從指定的router-compiler生成的目錄遍歷文件加載路由映射表routerMap,并緩存到SP幅骄;否則直接讀取SP中的routerMap
- (3)遍歷routerMap劫窒,根據(jù)className的類型依次初始化并存儲到內(nèi)存中。Warehose對應的三個map拆座。groupsIndex(gourp名-該分組下的所有映射關系類名)主巍、interceptorsIndex(優(yōu)先級-攔截器名)、providersIndex()
-
(4)_ARouter.afterInit().通過路由打開InterceptorService懂拾,遍歷Warehose中的interceptorsIndex煤禽,實例化對象并存儲到Warehose.interceptors
圖1-初始化流程
2-路由跳轉(zhuǎn)
跳轉(zhuǎn)的代碼從ARouter.getInstance()-->ARouter.build()
ARouter.getInstance().build("/test/activity").navigation();
ARouter.build()-->_ARouter.getInstance().build()
protected Postcard build(String path) {
if (TextUtils.isEmpty(path)) {
throw new HandlerException(Consts.TAG + "Parameter is invalid!");
} else {
//PathReplaceService是實現(xiàn)路徑動態(tài)變化,也就是重定向功能岖赋。
PathReplaceService pService = ARouter.getInstance().navigation(PathReplaceService.class);
if (null != pService) {
//拿到通過PathReplaceService修改后的path
path = pService.forString(path);
}
//@1.extractGroup(path)解析出group名
return build(path, extractGroup(path));
}
}
@1._ARouter.build方法檬果。返回一個Postcard對象用于存儲跳轉(zhuǎn)信息。Postcard繼承RouteMeta,封裝了路由類型选脊、@Autowired屬性集合Map(屬性名-屬性類型)等信息
protected Postcard build(String path, String group) {
if (TextUtils.isEmpty(path) || TextUtils.isEmpty(group)) {
throw new HandlerException(Consts.TAG + "Parameter is invalid!");
} else {
PathReplaceService pService = ARouter.getInstance().navigation(PathReplaceService.class);
if (null != pService) {
path = pService.forString(path);
}
return new Postcard(path, group);
}
}
然后調(diào)用_ARouter.navigation方法
protected Object navigation(final Context context, final Postcard postcard, final int requestCode, final NavigationCallback callback) {
杭抠。。恳啥。
try {
//@2.查找對應的路由信息
LogisticsCenter.completion(postcard);
} catch (NoRouteFoundException ex) {
logger.warning(Consts.TAG, ex.getMessage());
if (debuggable()) {
// Show friendly tips for user.
runInMainThread(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, "There's no route matched!\n" +
" Path = [" + postcard.getPath() + "]\n" +
" Group = [" + postcard.getGroup() + "]", Toast.LENGTH_LONG).show();
}
});
}
if (null != callback) {
//調(diào)用onLost回調(diào)
callback.onLost(postcard);
} else {
// 或者調(diào)用DegradeService全局降級的onLost處理
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()) { // 需要攔截處理
//@3.調(diào)用InterceptorService攔截
interceptorService.doInterceptions(postcard, new InterceptorCallback() {
@Override
public void onContinue(Postcard postcard) {
_navigation(context, postcard, requestCode, callback);
}
@Override
public void onInterrupt(Throwable exception) {
if (null != callback) {
callback.onInterrupt(postcard);
}
logger.info(Consts.TAG, "Navigation failed, termination by interceptor : " + exception.getMessage());
}
});
} else {//不需要攔截處理
//@3.最終跳轉(zhuǎn)
return _navigation(context, postcard, requestCode, callback);
}
return null;
}
@2.LogisticsCenter.completion方法偏灿。主要工作就是從Warehouse中懶加載路由信息并緩存到Postcard,包括@Autowired注解的參數(shù)列表封裝到Postecard的mBundle中
public synchronized static void completion(Postcard postcard) {
if (null == postcard) {
throw new NoRouteFoundException(TAG + "No postcard!");
}
RouteMeta routeMeta = Warehouse.routes.get(postcard.getPath());
if (null == routeMeta) { // Maybe its does't exist, or didn't load.
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()));
}
//從Warehouse.groupIndex讀取到對應的映射列表钝的。并將列表中的路由加到Warehouse.routes
//同時已加載的group從groupIndex中移除
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 {
//將路由參數(shù)存儲到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());
}
switch (routeMeta.getType()) {
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;
}
}
}
@3.跳轉(zhuǎn)_navigation
- Activity翁垂。則構建Intent,將相關信息封裝到Intent硝桩,包括action沿猜、bundle等。在主線程調(diào)用startActivity跳轉(zhuǎn)碗脊。
- Fragment啼肩。創(chuàng)建Fragment實例,設置bundle參數(shù)衙伶,返回該Fragment實例
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
final Intent intent = new Intent(currentContext, postcard.getDestination());
intent.putExtras(postcard.getExtras());
// 設置Activity啟動模式
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);
}
// 設置Actions
String action = postcard.getAction();
if (!TextUtils.isEmpty(action)) {
intent.setAction(action);
}
// 主線程調(diào)用startActivity跳轉(zhuǎn)
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 {
//生成fragment實例
Object instance = fragmentMeta.getConstructor().newInstance();
//設置bundle參數(shù)
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());
}
//返回fragment實例
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;
}
跳轉(zhuǎn)過程總結:封裝Postcard -> 查找信息集合祈坠,實例化目標類 -> 返回實例或者跳轉(zhuǎn)。
- (1)ARouter.getInstance().build()-->_ARouter.getInstance().build()
- (2)PathReplaceService執(zhí)行path重定向
- (3)_ARouter.navigation-->LogisticsCenter.completion矢劲。
- (4)Warehouse的routes中取路由參數(shù)赦拘,獲取失敗則解析groupsIndex中對應group的路由列表,添加到routes中卧须。
- (5)添加完畢再次從routes獲取另绩,將路由參數(shù)封裝到Poster并返回
- (6)啟動InterceptorService執(zhí)行攔截器
-
(7)執(zhí)行_navigation。若是Activity花嘶,則將poster信息封裝到Intent,通過在主線程startActivity跳轉(zhuǎn)蹦漠。若是Fragment椭员,根據(jù)poster信息創(chuàng)建Fragment實例并返回
圖2-跳轉(zhuǎn)流程
3-@Interceptor攔截
@4.InterceptorService的doInterceptions進行攔截處理。通過CountDownLatch實現(xiàn)計數(shù)阻塞笛园。計數(shù)初始值為攔截器個數(shù)隘击,每執(zhí)行一個攔截器操作計數(shù)-1。計數(shù)為0或timeout則取消線程阻塞
@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() {
//攔截器個數(shù)作為計數(shù)初始值
CancelableCountDownLatch interceptorCounter = new CancelableCountDownLatch(Warehouse.interceptors.size());
try {
_excute(0, interceptorCounter, postcard);
//阻塞線程直到超時研铆,或者計數(shù)歸0
interceptorCounter.await(postcard.getTimeout(), TimeUnit.SECONDS);
if (interceptorCounter.getCount() > 0) { //攔截超時
callback.onInterrupt(new HandlerException("The interceptor processing timed out."));
} else if (null != postcard.getTag()) { // 被攔截
callback.onInterrupt(new HandlerException(postcard.getTag().toString()));
} else { //放行
callback.onContinue(postcard);
}
} catch (Exception e) {
callback.onInterrupt(e);
}
}
});
} else {
callback.onContinue(postcard);
}
}
/**
* Excute interceptor
*
* @param index current interceptor index
* @param counter interceptor counter
* @param postcard routeMeta
*/
private static void _excute(final int index, final CancelableCountDownLatch counter, final Postcard postcard) {
//有下一個攔截器
if (index < Warehouse.interceptors.size()) {
IInterceptor iInterceptor = Warehouse.interceptors.get(index);
iInterceptor.process(postcard, new InterceptorCallback() {
@Override
public void onContinue(Postcard postcard) {
// 如果放行埋同,則計數(shù)減1,執(zhí)行后一個攔截器
counter.countDown();
_excute(index + 1, counter, postcard);
}
@Override
public void onInterrupt(Throwable exception) {
// 攔截棵红,將exception存入postcard的tag字段凶赁,計數(shù)歸零
postcard.setTag(null == exception ? new HandlerException("No message.") : exception.getMessage());
counter.cancel();
});
}
}
4-@Autowired參數(shù)注解
@Route(path = "/arouter/service/autowired")
public class AutowiredServiceImpl implements AutowiredService {
private LruCache<String, ISyringe> classCache;
private List<String> blackList;
@Override
public void init(Context context) {
classCache = new LruCache<>(66);
blackList = new ArrayList<>();
}
@Override
public void autowire(Object instance) {
String className = instance.getClass().getName();
try {
if (!blackList.contains(className)) {
ISyringe autowiredHelper = classCache.get(className);
if (null == autowiredHelper) { // No cache.
autowiredHelper = (ISyringe) Class.forName(instance.getClass().getName() + SUFFIX_AUTOWIRED).getConstructor().newInstance();
}
//從mBundle中取出參數(shù)賦值
autowiredHelper.inject(instance);
classCache.put(className, autowiredHelper);
}
} catch (Exception ex) {
blackList.add(className); // This instance need not autowired.
}
}
}
ISyringe是apt在注解@Autowired時自動生成一個對應的ISyringe實現(xiàn)。將bundle中的數(shù)據(jù)取出,賦值給@Autowired注解的屬性虱肄。
總的參數(shù)注入過程:
- ARouter.inject-->_ARouter.inject
- AutowiredServiceImpl.autowire
- 生成apt自動生成的ISyringe類的實例
- ISyringe致板。inject將Poster中的mBundle參數(shù)賦值給具體的屬性
先通過開啟AutowiredService來實現(xiàn)