Android Ali routing framework ARouter
1: Foreword
As the project becomes larger and larger, some projects have exceeded 100M, which will bring a lot of problems. As the amount of code increases, the AS compilation time increases, and the coupling of the code increases. Android componentization can solve these 2 Point problems, componentization brings problems, how do we solve the communication problems of components, the page call problems between components, etc., Alibaba routing ARouter provides a good solution
2: ARouter uses
1. Add dependency:
The first step: add in the basic moudle_base library
dependencies {
compile 'com.alibaba:arouter-api:1.5.0'
annotationProcessor 'com.alibaba:arouter-compiler:1.2.2'
}
The second step: add in the business component, for example: moudle_login and other modules
dependencies {
annotationProcessor 'com.alibaba:arouter-compiler:1.2.2'
}
Step 3: Configure the android defaultConfig under build.gradle in the module
android{
defaultConfig {
//Arouter路由配置,第三步配置信息
javaCompileOptions {
annotationProcessorOptions {
arguments = [AROUTER_MODULE_NAME: project.getName()]
includeCompileClasspath = true
}
}
}
}
2. Initialize ARouter in Application in App module
private void initRouter() {
//这两行必须写在init之前,否则这些配置在init过程中无效
if (AppUtils.isAppDebug()) {//第三方工具判断是否是Debug 或者BuildConfig.DEBUG
//打印日志
ARouter.openLog();
//开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险)
ARouter.openDebug();
}
ARouter.init(mApplication);
}
3. Process analysis
The interface jumps to the B interface, and the aouter does the following:
From the above process, we can find the principle in Arouter:
1. Use apt technology to use annotations to generate classes when compiling to encapsulate the class information of the target interface class.
2. During initialization, the compiled class is stored in the router through key-value.
3. The sending operator obtains the information of the target interface class through the key.
4. Combine or associate the sending operator's information with the target interface information.
5. Realize the jump function.
In fact, a simple summary: Pass the interface information that needs to jump to each other to store the association in the router & realize the jump.
4. Routing usage
4.1 Jump page without parameters
Send jump operation
// 1. 普通跳转
ARouter.getInstance().build("/test/LoginActivity").navigation();
Target page
// 在支持路由的页面上添加注解(必选)
// 这里的路径需要注意的是至少需要有两级,/xx/xx
@Route(path = "/test/LoginActivity")
public class LoginActivity extend Activity {
...
}
We define a RouterUtils tool class to manage these routing jump paths in a unified manner
public class RouterUtils {
/**
* 定义一个RouterUtils工具类
*/
//定义一个Group,ARouter路由第一个层级代表一个组别
public static final String LOGIN_GROUP = "/login";
public static final String LoginActivity=LOGIN_GROUP+"/LoginActivity";
public static final String WebViewActivity=LOGIN_GROUP+"/WebViewActivity";
}
5.2 Jump interface with parameters
Send a jump
ARouter.getInstance().build(RouterUtils.WebViewActivity).withString("url", getString(R.string.help_center)).navigation();
Target page
@Route(path = RouterUtils.WebViewActivity)
public class WebViewActivity extends BaseActivity {
//获取数据三种方式
//1.通过Autowired注解表明key & 需要在onCreate中调用ARouter.getInstance().inject(this);配合使用
@Autowired(name = "key1")
public long data;
//2.通过Autowired注解 & 将key1作为属性的名称 & 需要在onCreate中调用ARouter.getInstance().inject(this);配合使用
@Autowired()
public long key1;
//前两种没怎么用过
//3.获取数据,通过Bundle
String url=getIntent().getStringExtra("url");
LogUtils.d("initData: url=" + url);
}
5.3 Uri jump
Interface configuration
<activity android:name=".activity.SchameFilterActivity">
<!-- Schame -->
<intent-filter>
<data
android:host="m.aliyun.com"
android:scheme="arouter"/>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
</intent-filter>
</activity
Send jump operation
Uri testUriMix = Uri.parse("arouter://m.aliyun.com/test/activity2");
ARouter.getInstance().build(testUriMix)
.withString("key1", "value1")
.navigation();
Target page
@Route(path = "/test/activity2")
public class Test2Activity extends AppCompatActivity {
}
5.4 Monitoring of Jump Page Results
ARouter.getInstance()
.build("/test/activity2")
.navigation(this, new NavCallback() {
@Override
public void onArrival(Postcard postcard) {
}
@Override
public void onInterrupt(Postcard postcard) {
Log.d("ARouter", "被拦截了");
}
});
5.5 Declare the interceptor (intercept the jump process, aspect-oriented programming)
// 比较经典的应用就是在跳转过程中处理登陆事件,这样就不需要在目标页重复做登陆检查
// 拦截器会在跳转之间执行,多个拦截器会按优先级顺序依次执行
@Interceptor(priority = 8, name = "测试用拦截器")
public class TestInterceptor implements IInterceptor {
@Override
public void process(Postcard postcard, InterceptorCallback callback) {
...
callback.onContinue(postcard); // 处理完成,交还控制权
// callback.onInterrupt(new RuntimeException("我觉得有点异常")); // 觉得有问题,中断路由流程
// 以上两种至少需要调用其中一种,否则不会继续路由
}
@Override
public void init(Context context) {
// 拦截器的初始化,会在sdk初始化的时候调用该方法,仅会调用一次
}
}
5.6 Declare more information for the target page
// 我们经常需要在目标页面中配置一些属性,比方说"是否需要登陆"之类的
// 可以通过 Route 注解中的 extras 属性进行扩展,这个属性是一个 int值,换句话说,单个int有4字节,也就是32位,可以配置32个开关
// 剩下的可以自行发挥,通过字节操作可以标识32个开关,通过开关标记目标页面的一些属性,在拦截器中可以拿到这个标记进行业务逻辑判断
@Route(path = "/test/activity", extras = Consts.XXXX)
5.7 Dependency Injection Decoupling
Register objects that require dependency injection
@Route(path = "/provider/testP")
public class TestProvider implements IProvider {
@Override
public void init(Context context) {
}
public String test(){
return ("Hello Provider!");
}
}
Get object & use
ARouter.getInstance().navigation(TestProvider.class).test();
ARouter's GitHub: https://github.com/alibaba/ARouter/blob/master/README_CN.md There are many routes using
3: Analysis of routing ARouter structure
ARouter is mainly composed of three parts, including externally provided API call modules, annotation modules, and related class modules produced through annotations at compile time.
- Arouter-annotation annotated declaration and information storage module
- arouter-compiler module that parses annotation information during compile time and generates corresponding classes for injection
- arouter-api core calling Api function module
annotation module
Route (path), Interceptor (intercept), Autowired (data acquisition) are all annotations needed in development
Compiler module, this is the file generated by compilation
AutoWiredProcessor (automatic assembly processor), InterceptorProcessor (interceptor processor), RouteProcessor (route path processor) are the Autowired, Interceptor, and Route corresponding to the annotation module to generate related class files when the project is compiled.
api module
Mainly the specific implementation of ARouter and the api used for external exposure
: Knowledge learning, from
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。