- Intent intent = new Intent(mContext, XxxActivity.class);
- intent.putExtra("key","value");
- startActivity(intent);
-
- Intent intent = new Intent(mContext, XxxActivity.class);
- intent.putExtra("key","value");
- startActivityForResult(intent, 666);
- android {
- defaultConfig {
- ...
- javaCompileOptions {
- annotationProcessorOptions {
- arguments = [AROUTER_MODULE_NAME: project.getName()]
- }
- }
- }
- }
-
- dependencies {
- // 替换成最新版本, 需要注意的是api
- // 要与compiler匹配使用,均使用最新版可以保证兼容
- compile 'com.alibaba:arouter-api:x.x.x'
- annotationProcessor 'com.alibaba:arouter-compiler:x.x.x'
- }
- apply plugin: 'com.alibaba.arouter'
-
- buildscript {
- repositories {
- jcenter()
- }
-
- dependencies {
- classpath "com.alibaba:arouter-register:?"
- }
- }
- -keep public class com.alibaba.android.arouter.routes.**{*;}
- -keep public class com.alibaba.android.arouter.facade.**{*;}
- -keep class * implements com.alibaba.android.arouter.facade.template.ISyringe{*;}
-
- # 如果使用了 byType 的方式获取 Service,需添加下面规则,保护接口
- -keep interface * implements com.alibaba.android.arouter.facade.template.IProvider
-
- # 如果使用了 单类注入,即不定义接口实现 IProvider,需添加下面规则,保护实现
- # -keep class * implements com.alibaba.android.arouter.facade.template.IProvider
- // 更新 build.gradle, 添加参数 AROUTER_GENERATE_DOC = enable
- // 生成的文档路径 : build/generated/source/apt/
- // (debug or release)/com/alibaba/android/arouter/docs/arouter-map-of-${moduleName}.json
- android {
- defaultConfig {
- ...
- javaCompileOptions {
- annotationProcessorOptions {
- arguments = [AROUTER_MODULE_NAME: project.getName(), AROUTER_GENERATE_DOC: "enable"]
- }
- }
- }
- }
- public static void initRouter(Application application) {
- if (BuildConfig.DEBUG) { // 这两行必须写在init之前,否则这些配置在init过程中将无效
- ARouter.openLog(); // 打印日志
- // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险)
- ARouter.openDebug();
- }
- ARouter.init(application); // 尽可能早,推荐在Application中初始化
- }
- // 在支持路由的页面上添加注解(必选)
- // 这里的路径需要注意的是至少需要有两级,/xx/xx
- @Route(path = "/test/activity")
- public class YourActivity extend Activity {
- ...
- }
- // 1. 应用内简单的跳转(通过URL跳转在'进阶用法'中)
- ARouter.getInstance().build("/test/activity").navigation();
-
- // 2. 跳转并携带参数
- ARouter.getInstance().build("/test/1")
- .withLong("key1", 666L)
- .withString("key3", "888")
- .withObject("key4", new Test("Jack", "Rose"))
- .navigation();
ARouter跳转到其他moudle时,需要注意的是,moudle中的目标Activity或者service服务类上使用@Route(path = “xx/xxx”) 与 app moudle中使用的@Route里的path路径不能相同,否则会报错,找不到索引。步骤一:鼠标右键项目 -> New -> Module -> 直至创建完成;步骤二:注释掉module中build.gradle里面相应的配置,如:(applicationId 和apply plugin等)同时引入ARouter中的依赖库,同app module;步骤三:删除module中AndoridManifest.xml中不需要的配置;步骤四:为module中的目标页面配置路由步骤五:实现module之间的跳转。
- /**
- * Path of route
- */
- String path();
-
- /**
- * Used to merger routes, the group name must be use the common words !!!
- */
- String group() default "";
-
- /**
- * Name of route, used to generate javadoc.
- */
- String name() default "";
-
- /**
- * Extra data, 可以被用户设置
- * Ps. U should use the integer num sign the switch, by bits. 10001010101010
- */
- int extras() default Integer.MIN_VALUE;
-
- /**
- * The priority of route.
- * 值越小,优先级越高
- */
- int priority() default -1;
- @OnClick(R2.id.enter_activity_inject)
- public void onClick9() {
- TestSerializable testSerializable = new TestSerializable("Titanic", 555);
- TestParcelable testParcelable = new TestParcelable("jack", 666);
- TestObj testObj = new TestObj("Rose", 777);
- List
objList = new ArrayList<>(); - objList.add(testObj);
-
- Map
> map = new HashMap<>(); - map.put("testMap", objList);
-
- ARouter.getInstance().build("/self/activity_inject")
- .withString("name", "老王")
- .withInt("age", 18)
- .withBoolean("boy", true)
- .withLong("high", 180)
- .withString("url", "https://a.b.c")
- .withSerializable("ser", testSerializable)
- .withParcelable("pac", testParcelable)
- .withObject("obj", testObj)
- .withObject("objList", objList)
- .withObject("map", map)
- .navigation();
- }
- @Autowired(desc = "姓名")
- String name = "jack";
-
- @Autowired
- int age = 10;
-
- @Autowired
- int height = 175;
-
- //通过name来映射URL中的不同参数,及girl是传递参数时的字段名,在当前,可以改变字段名称,使用boy替换girl。
- @Autowired(name = "boy", required = true)
- boolean girl;
-
- @Autowired
- char ch = 'A';
-
- @Autowired
- float fl = 12.00f;
-
- @Autowired
- double dou = 12.01d;
-
- @Autowired
- TestSerializable ser;
-
- @Autowired
- TestParcelable pac;
-
- // URL中不能传递Parcelable类型数据,通过ARouter api可以传递Parcelable对象
- // 支持解析自定义对象,URL中使用json传递
- @Autowired
- TestObj obj;
-
- //使用withObject传递实现Serializable接口ArrayList和HashMap的时候,
- //接收对象的地方不能标注为具体实现的类型,否则会影响序列化中类型的判断,
- //应该标注为:List 和 Map.
- @Autowired
- List
objList; - @Autowired
- Map
> map; -
- @Autowired
- String url;
-
- //获取服务实例的第三种方式 -- 通过注解获取
- @Autowired
- HelloService helloService;
- // 如果需要传递自定义对象,新建一个类(并非自定义对象类),
- // 然后实现 SerializationService, 并使用@Route注解标注(方便用户自行选择序列化方式),例如
- @Route(path = "/self_service/json")
- public class JsonServiceImpl implements SerializationService {
- @Override
- public void init(Context context) {
-
- }
-
- //json字符串转换为对象
- @Override
- public
T json2Object(String text, Class clazz) { - return JSON.parseObject(text, clazz);
- }
-
- //自定义对象转换为json字符串
- @Override
- public String object2Json(Object instance) {
- return JSON.toJSONString(instance);
- }
-
- @Override
- public
T parseObject(String input, Type clazz) { - return JSON.parseObject(input, clazz);
- }
- }
- <p>
- <a href="arouter://m.aliyun.com/test/activity1?name=tpnet&age=21&sex=true&obj=%7B%22name%22:%22jack%22,%22id%22:666%7D">
- 带json自定义对象
- a>
- p>
- public class TestObj() {
- //这里变量名称对应Url的json的key
- public String name;
- public int id;
- }
- @AutoWired
- String name;
-
- @AutoWired(name = “id”)
- int ID;
- /**
- * 自定义拦截器
- * priority: 为拦截器的优先级,其值越小,优先级越高;多个拦截器时候有用;
- */
- @Interceptor(priority = 7, name = "测试用拦截器")
- public class Test1Interceptor implements IInterceptor {
- Context mContext;
- /**
- * process:拦截器操作
- * @param postcard 数据
- * @param callback 回调
- */
- @Override
- public void process(final Postcard postcard, final InterceptorCallback callback) {
- if ("/self/activity_page".equals(postcard.getPath())) {
- // 这里的弹窗仅做举例,代码写法不具有可参考价值
- final AlertDialog.Builder ab = new AlertDialog.Builder(ARouterHomeActivity.getThis());
- ab.setCancelable(false);
- ab.setTitle("温馨提醒");
- ab.setMessage(
- "想要跳转到ARouterPageActivity么?(触发了\"/inter/test\"拦截器,拦截了本次跳转)”
- );
- ab.setNegativeButton("继续", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- //继续执行跳转,不做额外的拦截操作
- callback.onContinue(postcard);
- }
- });
- ab.setNeutralButton("算了", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- //直接终止跳转
- callback.onInterrupt(null);
- callback.onInterrupt(new RuntimeException("出现跳转终止的异常"));
- }
- });
- ab.setPositiveButton("加参数", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- postcard.withString("extra", "这拦截器中附加的参数");
- callback.onContinue(postcard);
- }
- });
- MainLooper.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- ab.create().show();
- }
- });
- } else {
- callback.onContinue(postcard);
- }
- }
- /**
- * 拦截器的初始化,会在sdk初始化的时候调用该方法,且仅会调用一次;
- */
- @Override
- public void init(Context context) {
- mContext = context;
- Log.e("testService", Test1Interceptor.class.getName() + " has init.");
- }
- }
- // 声明接口,其他组件通过接口来调用服务
- public interface HelloService implements IProvider {
- String sayHello(String name);
- }
-
- // 实现接口
- @Route(path = "/yourservicegroupname/hello", name = "测试服务")
- public class HelloServiceImpl implements HelloService {
-
- @Override
- public String sayHello(String name) {
- return "hello, " + name;
- }
-
- @Override
- public void init(Context context) {
-
- }
- }
- public class Test {
- //注解的方式获取服务
- @Autowired
- HelloService helloService;
-
- //注解的方式获取服务—重命名服务
- @Autowired(name = "/yourservicegroupname/hello")
- HelloService helloService2;
-
- //其他方式获取服务
- HelloService helloService3;
- HelloService helloService4;
-
-
- public Test() {
- //这里是重点********** 出过错,忘记在使用 Aroter的组件(Activity)中注册了
- ARouter.getInstance().inject(this);
- }
-
-
- public void testService() {
- // 1. (推荐)使用依赖注入的方式发现服务,通过注解标注字段,即可使用,无需主动获取
- // Autowired注解中标注name之后,将会使用byName的方式注入对应的字段,
- // 不设置name属性,会默认使用byType的方式发现服务
- // (当同一接口有多个实现的时候,必须使用byName的方式发现服务)
- helloService.sayHello("Vergil");
- helloService2.sayHello("Vergil");
-
- // 2. 使用依赖查找的方式发现服务,主动去发现服务并使用,下面两种方式分别是byName和byType
- helloService3 = ARouter.getInstance().navigation(HelloService.class);
- helloService4 = (HelloService) ARouter.getInstance().build("/yourservicegroupname/hello").navigation();
- helloService3.sayHello("Vergil");
- helloService4.sayHello("Vergil");
- }
- }
3、预处理服务
- // 实现 PretreatmentService 接口,并加上一个Path内容任意的注解即可
- @Route(path = "/xxx/xxx")
- public class PretreatmentServiceImpl implements PretreatmentService {
- @Override
- public boolean onPretreatment(Context context, Postcard postcard) {
- // 跳转前预处理,如果需要自行处理跳转,该方法返回 false 即可
- }
-
- @Override
- public void init(Context context) {
-
- }
- }
4、重写跳转Url的服务
- @Route(path = "/self/repace_pathorurl_service")
- public class ReplacePathOrUrlServiceImpl implements PathReplaceService {
- Context mContext;
-
- /**
- * void 重写跳转路径path
- * @param path 原始的跳转路径
- * @return 按照一定的规则处理之后返回处理后的结果
- */
- @Override
- public String forString(String path) {
- return path;
- }
-
- /**
- * void 重写跳转Uri
- * @param uri 原始的跳转url
- * @return 按照一定的规则处理之后返回处理后的结果
- */
- @Override
- public Uri forUri(Uri uri) {
- return uri;
- }
-
- @Override
- public void init(Context context) {
- this.mContext = context;
- }
// 我们经常需要在目标页面中配置一些属性,比方说"是否需要登陆”之类的,// 可以通过 Route 注解中的 extras 属性进行扩展,这个属性是一个 int值,// 换句话说,单个int有4字节,也就是32位,可以配置32个开关// 剩下的可以自行发挥,通过字节操作可以标识32个开关,通过开关标记目标页面的一些属性,// 在拦截器中可以拿到这个标记进行业务逻辑判断@Route(path = "/test/activity", extras = Consts.XXXX)
- //构建标准的路由请求
- ARouter.getInstance().build("/home/main").navigation();
-
- //构建标准的路由请求,并指定分组
- ARouter.getInstance().build("/home/main", "ap").navigation();
-
- //构建标准的路由请求,通过Uri直接解析
- Uri uri;
- ARouter.getInstance().build(uri).navigation();
-
- //构建标准的路由请求,startActivityForResult
- //navigation的第一个参数必须是Activity,第二个参数则是RequestCode
- ARouter.getInstance().build("/home/main", "ap").navigation(this, 5);
-
- //直接传递Bundle
- Bundle params = new Bundle();
- ARouter.getInstance()
- .build("/home/main")
- .with(params)
- .navigation();
-
- //指定Flag
- ARouter.getInstance()
- .build("/home/main")
- .withFlags();
- .navigation();
-
- //获取Fragment
- Fragment fragment = (Fragment) ARouter.getInstance().build("/test/fragment").navigation();
-
- //对象传递
- ARouter.getInstance()
- .withObject("key", new TestObj("Jack", "Rose"))
- .navigation();
-
- //觉得接口不够多,可以直接拿出Bundle赋值
- ARouter.getInstance()
- .build("/home/main")
- .getExtra();
-
- //转场动画(常规方式)
- ARouter.getInstance()
- .build("/test/activity2")
- .withTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom)
- .navigation(this);
-
- //转场动画(API16+)
- ActivityOptionsCompat compat = ActivityOptionsCompat.
- makeScaleUpAnimation(v, v.getWidth() / 2, v.getHeight() / 2, 0, 0);
- //ps. makeSceneTransitionAnimation 使用共享元素的时候,需要在navigation方法中传入当前Activity
-
- ARouter.getInstance()
- .build("/test/activity2")
- .withOptionsCompat(compat)
- .navigation();
-
- //使用绿色通道(跳过所有的拦截器)
- ARouter.getInstance().build("/home/main").greenChannel().navigation();
-
- //使用自己的日志工具打印日志
- ARouter.setLogger();
-
- //获取原始的URI
- String uriStr = getIntent().getStringExtra(ARouter.RAW_URI);
-
- //关闭ARouter
- ARouter.getInstance().destroy();