// _ARouter.java/**
* 根据 path 构建一个 Postcard 对象
*/protectedPostcardbuild(String path){if(TextUtils.isEmpty(path)){thrownewHandlerException(Consts.TAG +"Parameter is invalid!");}else{// 获取 PathReplaceService 服务,对外提供修改路由 path 和 uri(只需要重写该类)PathReplaceService pService =ARouter.getInstance().navigation(PathReplaceService.class);if(null!= pService){
path = pService.forString(path);}returnbuild(path,extractGroup(path),true);}}/**
* 根据 uri 构建一个 Postcard 对象
*/protectedPostcardbuild(Uri uri){if(null== uri ||TextUtils.isEmpty(uri.toString())){thrownewHandlerException(Consts.TAG +"Parameter invalid!");}else{// 获取 PathReplaceService 服务,对外提供修改路由 path 和 uri(只需要重写该类)PathReplaceService pService =ARouter.getInstance().navigation(PathReplaceService.class);if(null!= pService){
uri = pService.forUri(uri);}// 创建一个 Postcard 对象returnnewPostcard(uri.getPath(),extractGroup(uri.getPath()), uri,null);}}/**
* 根据 path 和 group 构建一个 Postcard 对象
*/protectedPostcardbuild(String path,String group,Boolean afterReplace){if(TextUtils.isEmpty(path)||TextUtils.isEmpty(group)){thrownewHandlerException(Consts.TAG +"Parameter is invalid!");}else{if(!afterReplace){// 获取 PathReplaceService 服务,对外提供修改路由 path 和 uri(只需要重写该类)PathReplaceService pService =ARouter.getInstance().navigation(PathReplaceService.class);if(null!= pService){
path = pService.forString(path);}}// 创建一个 Postcard 对象returnnewPostcard(path, group);}}/**
* 根据路径获取 Group
*/privateStringextractGroup(String path){// 如果不是以/开头,编译期可以通过编译只是不创建对应的类// 如果是空或者不是以/开头 则直接抛出异常if(TextUtils.isEmpty(path)||!path.startsWith("/")){thrownewHandlerException(Consts.TAG +"Extract the default group failed, the path must be start with '/' and contain more than 2 '/'!");}try{String defaultGroup = path.substring(1, path.indexOf("/",1));if(TextUtils.isEmpty(defaultGroup)){thrownewHandlerException(Consts.TAG +"Extract the default group failed! There's nothing between 2 '/'!");}else{return defaultGroup;}}catch(Exception e){
logger.warning(Consts.TAG,"Failed to extract default group! "+ e.getMessage());returnnull;}}protectedObjectnavigation(finalContext context,finalPostcard postcard,finalint requestCode,finalNavigationCallback callback){// 获取 PretreatmentService 路由预处理服务,对外提供修改路由能力PretreatmentService pretreatmentService =ARouter.getInstance().navigation(PretreatmentService.class);if(null!= pretreatmentService &&!pretreatmentService.onPretreatment(context, postcard)){// Pretreatment failed, navigation canceled.returnnull;}// Set context to postcard.
postcard.setContext(null== context ? mContext : context);try{// 执行 completion// 填充 postcardLogisticsCenter.completion(postcard);}catch(NoRouteFoundException ex){
logger.warning(Consts.TAG, ex.getMessage());if(debuggable()){// Show friendly tips for user.runInMainThread(newRunnable(){@Overridepublicvoidrun(){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.// 如果上一步发送错误,且没有 callback 回调// 获取 DegradeService 全局降级服务,对外提供修改路由能力,出错策略自定义的机会DegradeService degradeService =ARouter.getInstance().navigation(DegradeService.class);if(null!= degradeService){
degradeService.onLost(context, postcard);}}returnnull;}if(null!= callback){// 执行成功回调
callback.onFound(postcard);}// Provider 和 Fragment 不走拦截器if(!postcard.isGreenChannel()){// 必须在异步线程中运行,也许拦截器花费太多时间导致 ANR。// 执行拦截器的 doInterceptions() 方法
interceptorService.doInterceptions(postcard,newInterceptorCallback(){/**
* Continue process 没有中断的回调
*
* @param postcard route meta
*/@OverridepublicvoidonContinue(Postcard postcard){// 如果没有中断最终将执行该方法_navigation(postcard, requestCode, callback);}/**
* 中断的回调
* Interrupt process, pipeline will be destory when this method called.
*
* @param exception Reson of interrupt.
*/@OverridepublicvoidonInterrupt(Throwable exception){if(null!= callback){
callback.onInterrupt(postcard);}
logger.info(Consts.TAG,"Navigation failed, termination by interceptor : "+ exception.getMessage());}});}else{return_navigation(postcard, requestCode, callback);}returnnull;}
// LogisticsCenter.javapublicsynchronizedstaticvoidcompletion(Postcard postcard){if(null== postcard){thrownewNoRouteFoundException(TAG +"No postcard!");}// 根据路径查看当前已经按组加载过的 RouteMeta 是否在内存中存在,从而获取 RouteMetaRouteMeta routeMeta =Warehouse.routes.get(postcard.getPath());if(null== routeMeta){// 首次调用 routeMeta 为 null// 如果 map 中不包含 postcard 的 group 则抛出异常if(!Warehouse.groupsIndex.containsKey(postcard.getGroup())){thrownewNoRouteFoundException(TAG +"There is no route match the path ["+ postcard.getPath()+"], in group ["+ postcard.getGroup()+"]");}else{// 加载路由并将其缓存到内存中,然后从元数据中删除try{if(ARouter.debuggable()){
logger.debug(TAG,String.format(Locale.getDefault(),"The group [%s] starts loading, trigger by [%s]", postcard.getGroup(), postcard.getPath()));}// 将属于这个 group 中的所有路由都添加到 map 中addRouteGroupDynamic(postcard.getGroup(),null);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){thrownewHandlerException(TAG +"Fatal exception when loading group meta. ["+ e.getMessage()+"]");}// 再次执行 completion() 方法completion(postcard);}}else{// 设置目标
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 @Paramfor(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(newString[]{}));}// Save raw uri
postcard.withString(ARouter.RAW_URI, rawUri.toString());}switch(routeMeta.getType()){case PROVIDER:// 如果是 Provider 类型,应该找到它的实例
// 如果是 Provider 必须实现 IProvider 接口// 创建 Provider 实例Class<?extendsIProvider> providerMeta =(Class<?extendsIProvider>) routeMeta.getDestination();// 从缓存中获取 ProviderIProvider instance =Warehouse.providers.get(providerMeta);if(null== instance){IProvider provider;try{// 如果为空,通过反射的方式创建 IProvider
provider = providerMeta.getConstructor().newInstance();
provider.init(mContext);Warehouse.providers.put(providerMeta, provider);
instance = provider;}catch(Exception e){
logger.error(TAG,"Init provider failed!", e);thrownewHandlerException("Init provider failed!");}}
postcard.setProvider(instance);
postcard.greenChannel();// 默认 Provider 和 Fragment 不走拦截器break;case FRAGMENT:
postcard.greenChannel();// 默认 Provider 和 Fragment 不走拦截器default:break;}}}
// LogisticsCenter.javapublicsynchronizedstaticvoidcompletion(Postcard postcard){...if(MapUtils.isNotEmpty(paramsType)){// Set value by its type, just for params which annotation by @Paramfor(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(newString[]{}));}...}privatestaticvoidsetValue(Postcard postcard,Integer typeDef,String key,String value){if(TextUtils.isEmpty(key)||TextUtils.isEmpty(value)){return;}try{if(null!= typeDef){if(typeDef ==TypeKind.BOOLEAN.ordinal()){
postcard.withBoolean(key,Boolean.parseBoolean(value));}elseif(typeDef ==TypeKind.BYTE.ordinal()){
postcard.withByte(key,Byte.parseByte(value));}elseif(typeDef ==TypeKind.SHORT.ordinal()){
postcard.withShort(key,Short.parseShort(value));}elseif(typeDef ==TypeKind.INT.ordinal()){
postcard.withInt(key,Integer.parseInt(value));}elseif(typeDef ==TypeKind.LONG.ordinal()){
postcard.withLong(key,Long.parseLong(value));}elseif(typeDef ==TypeKind.FLOAT.ordinal()){
postcard.withFloat(key,Float.parseFloat(value));}elseif(typeDef ==TypeKind.DOUBLE.ordinal()){
postcard.withDouble(key,Double.parseDouble(value));}elseif(typeDef ==TypeKind.STRING.ordinal()){
postcard.withString(key, value);}elseif(typeDef ==TypeKind.PARCELABLE.ordinal()){// TODO : How to description parcelable value with string?}elseif(typeDef ==TypeKind.OBJECT.ordinal()){
postcard.withString(key, value);}else{// Compatible compiler sdk 1.0.3, in that version, the string type = 18
postcard.withString(key, value);}}else{
postcard.withString(key, value);}}catch(Throwable ex){
logger.warning(Consts.TAG,"LogisticsCenter setValue failed! "+ ex.getMessage());}}
其最终的参数是传递到了 Postcard 类中的 mBundle 中。
(2)当我们在Activity的onCreate()方法中调用ARouter.getInstance().inject(this)注入参数和服务,通过@Autowired标记注解@Autowired @JvmField var name: String? = null,通过上述两者进行参数获取时: