1、根目录build.gradle中配置
repositories {
mavenCentral()
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
}
classpath 'com.alibaba:arouter-register:1.0.2'
2、某个module模块需要用到ARouter路由就在该module的build.gradle中配置如下代码
defaultConfig {
javaCompileOptions {
annotationProcessorOptions {
arguments = [AROUTER_MODULE_NAME: project.getName()]
}
}
}
implementation 'com.alibaba:arouter-api:1.5.0'
annotationProcessor 'com.alibaba:arouter-compiler:1.2.2'
3、Application中onCreate配置
if(BuildConfig.DEBUG){
ARouter.openDebug();
ARouter.openLog();
}
ARouter.init(this);
示例:
1、无参跳转,从A界面跳转B界面
A界面:
//注意build传的路径必须和B界面中的path对应,且必须'/'开头
ARouter.getInstance().build("/xx/B").navigation();
B界面:
@Route(path = "/xx/B")
public class B extends Activity
2、带参数跳转,从A界面跳转B界面
A界面:
//注意,with中的key必须和接收界面中的@Autowired定义的属性名保持一致
ARouter.getInstance()
.build("/xx/B")
.withString("userName","张无忌")
.withString("userPhone","185305555")
.withInt("age",20)
.navigation();
B界面:
//注意属性定义必须public,使用private会报异常
@Autowired
public String userName;
@Autowired
public String userPhone;
@Autowired
public int userAge;
//onCrtate初始化接入
ARouter.getInstance().inject(this);
//日志打印接收数据
Log.e("ARouter","userName:" + userName);
Log.e("ARouter","userPhone:" + userPhone);
Log.e("ARouter","userAge:" + userAge);
3、进阶学习,拦截器
LoginInterceptorImpl .java实现拦截逻辑
// 在跳转过程中处理登陆事件,这样就不需要在目标页重复做登陆检查
// 拦截器会在跳转之间执行,多个拦截器会按优先级顺序依次执行
@Interceptor(name = "login", priority = 1)
public class LoginInterceptorImpl implements IInterceptor {
@Override
public void process(Postcard postcard, InterceptorCallback callback) {
String path = postcard.getPath();
boolean isLogin = true;
if (isLogin) { // 如果已经登录不拦截
callback.onContinue(postcard);
} else { // 如果没有登录
switch (path) {
// 不需要登录的直接进入这个页面
case ActivityCommon.ModuleLogin.LoginActivity:
callback.onContinue(postcard);
break;
// 需要登录的直接拦截下来
default:
callback.onInterrupt(null);
break;
}
}
}
@Override
public void init(Context context) {//此方法只会走一次
}
}
LoginNavigationCallbackImpl.java实现跳转
public class LoginNavigationCallbackImpl implements NavigationCallback {
@Override //找到了
public void onFound(Postcard postcard) {
}
@Override //找不到了
public void onLost(Postcard postcard) {
}
@Override //跳转成功了
public void onArrival(Postcard postcard) {
}
@Override
public void onInterrupt(Postcard postcard) {
String path = postcard.getPath();
Bundle bundle = postcard.getExtras();
// 被登录拦截了下来了
// 需要调转到登录页面,把参数跟被登录拦截下来的路径传递给登录页面,登录成功后再进行跳转被拦截的页面
ARouter.getInstance().build(ActivityCommon.ModuleLogin.LoginActivity)
.with(bundle)
.navigation();
}
}
使用示例:
ARouter.getInstance()
.build(ActivityCommon.ModuleARouter.ARouterActivity)
.withString(ARouterActivity.USER_NAME, "张无忌")
.withString(ARouterActivity.USER_PHONE, "185305555")
.withInt(ARouterActivity.USER_AGE, 20)
.navigation(activity,new LoginNavigationCallbackImpl());