ARouter原理解析
2018-04-19 本文已影响350人
Rogge666
基于arouter-api:1.3.1 arouter-compiler:1.1.4
ARouter 为Android平台中对页面、服务提供路由功能的中间件
下面从源码分析为什么只用通过一个注解就可以得到相应的Activity或Fragment
//服务module中的FragmentService
@Route(path = "/service/fragmentService")
public class FragmentService{}
//服务module中的TestActivity
@Route(path = "/service/test")
public class TestActivity extends BaseActivity{}
//主APP中获取FragmentService实例
Fragment serviceFragment = (Fragment) ARouter.getInstance().build("/service/fragmentService").navigation();
//主APP中跳转服务module中的TestActivity
ARouter.getInstance().build("/service/test").navigation();
当使用@Route注解时 程序在编译期间会使用对应的注解处理器com.alibaba.android.arouter.compiler.processor.RouteProcessor 生成代码如下
image.png
//生成Group对应的代码(loadInto功能主要是在ARouter.init()时把Group放到group集合中)
public class ARouter$$Root$$service_module implements IRouteRoot {
@Override
public void loadInto(Map<String, Class<? extends IRouteGroup>> routes) {
routes.put("service", ARouter$$Group$$service.class);
}
}
//生成Group对应所有子节点的代码(loadInto功能主要是在APP第一次调用该group下的子节点时把所有的子节点加进集合中)
public class ARouter$$Group$$service implements IRouteGroup {
@Override
public void loadInto(Map<String, RouteMeta> atlas) {
atlas.put("/service/fragmentService", RouteMeta.build(RouteType.FRAGMENT, FragmentService.class, "/service/fragmentservice", "service", null, -1, -2147483648));
atlas.put("/service/test", RouteMeta.build(RouteType.ACTIVITY, TestActivity.class, "/service/test", "service", null, -1, -2147483648));
}
}
上面代码为程序编译时生成,在APP运行期间使用ARouter.init(Context);会调用如下代码
//_ARouter中init方法
protected static synchronized boolean init(Application application) {
mContext = application;
LogisticsCenter.init(mContext, executor);
logger.info(Consts.TAG, "ARouter init success!");
hasInit = true;
return true;
}
//LogisticsCenter精简版
public synchronized static void init(Context context, ThreadPoolExecutor tpe) throws HandlerException {
for (String className : routerMap) {
if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_ROOT)) {
((IRouteRoot) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.groupsIndex);
} else if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_INTERCEPTORS)) {
((IInterceptorGroup) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.interceptorsIndex);
} else if (className.startsWith(ROUTE_ROOT_PAKCAGE + DOT + SDK_NAME + SEPARATOR + SUFFIX_PROVIDERS)) {
((IProviderGroup) (Class.forName(className).getConstructor().newInstance())).loadInto(Warehouse.providersIndex);
}
}
}
}
通过反射把生成的文件全限定名取到加入routermap中然后通过反射实例化对应的类调用loadinto方法将group添加进如下集合之中
//Warehouse 精简源码
class Warehouse {
// group节点集合
static Map<String, Class<? extends IRouteGroup>> groupsIndex = new HashMap<>();
// group下子节点集合
static Map<String, RouteMeta> routes = new HashMap<>();
}
init完毕之后ARouter只把group节点初始化了
在APP调用ARouter.getInstance().build("/service/test").navigation();方法会调用如下源码
//_ARouter 中navigation()方法精简版
final class _ARouter {
protected Object _navigation(final Context context, final Postcard postcard, final int requestCode, final NavigationCallback callback) {
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);
}
// Navigation in main looper.
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (requestCode > 0) { // Need start for result
ActivityCompat.startActivityForResult((Activity) currentContext, intent, requestCode, postcard.getOptionsBundle());
} else {
ActivityCompat.startActivity(currentContext, intent, postcard.getOptionsBundle());
}
if ((0 != postcard.getEnterAnim() || 0 != postcard.getExitAnim()) && currentContext instanceof Activity) { // Old version.
((Activity) currentContext).overridePendingTransition(postcard.getEnterAnim(), postcard.getExitAnim());
}
if (null != callback) { // Navigation over.
callback.onArrival(postcard);
}
}
});
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;
}
}
在这里会把传入路径中的group解析出来查询对应的group下子节点是否已经被加到集合中,如果没有加入则通过loadinto加入,然后通过RouteMeta中的属性得到具体页面的类型和class名 进入_ARouter ._navigation()就获得了具体的Activity 其中Fragment需要根据全限定名反射得到实例,此时整个流程结束