组件化框架Arouter- 使用详解 alert组件
yuyutoo 2024-10-30 06:32 3 浏览 0 评论
ARouter是一款针对组件化模块之间无接触通讯的一个开源框架,ARouter主要作用:组件间通讯,组件解耦,路由跳转(涉及到常用的Activity,Provider,Fragment等多场景跳转)。
新建一个项目:Android Studio File-- New -- New Project:选择Phone and Tablet,选择Empty Views Activity.
- app:app模块:引入arouter的核心api和引用需要调用的模块即可
build.gradle:
dependencies {
...
implementation 'com.alibaba:arouter-api:1.5.2'
implementation project(':module_java')
implementation project(':module_kotlin')
//如果需要使用依赖注入的方式查找class对象,则需要添加声明注解处理器
annotationProcessor 'com.alibaba:arouter-compiler:1.5.2'
}
- module_java:java语言lib模块
build.gradle:
android {
javaCompileOptions {
annotationProcessorOptions {
arguments = [AROUTER_MODULE_NAME: project.getName(), AROUTER_GENERATE_DOC: "enable"]
}
}
}
dependencies {
...
implementation 'com.alibaba:arouter-api:1.5.2'
annotationProcessor 'com.alibaba:arouter-compiler:1.5.2'
}
1.引入arouter-api核心api和arouter-compiler注解处理器api
2.设置主机处理器的外部参数AROUTER_MODULE_NAME和AROUTER_GENERATE_DOC,这两个参数会在编译器生成Arouter路由表的时候使用到
- module_kotlin:kotli语言lib模块
build.gradle:
apply plugin: 'kotlin-kapt'
kapt {
arguments {
arg("AROUTER_MODULE_NAME", project.getName())
}
}
dependencies {
implementation 'com.alibaba:arouter-api:1.5.2'
kapt 'com.alibaba:arouter-compiler:1.5.2'
}
这里的设置方式和java一样,区别:java使用关键字 annotationProcessor,而kotlin使用 kapt。
同步项目后。就可以使用Arouter的api啦。
ARouter api
1.初始化Arouter
建议在application中初始化:
ARouter.init(this);
2.日志开启
ARouter.openLog();
3.打开调试模式
ARouter.openDebug();
调试模式不是必须开启,但是为了防止有用户开启了InstantRun,
忘了开调试模式,导致无法使用Demo,如果使用了InstantRun,必须在
初始化之前开启调试模式,但是上线前需要关闭,InstantRun仅用于开
发阶段,线上开启调试模式有安全风险,可以使用BuildConfig.DEBUG
来区分环境
4.Activity模块的调用:
- 4.1:注解声明
@Route(path = "/gtest/test")
//或者@Route(path = "/gtest/test",group = "gtest")
public class ArouterTestActivity extends AppCompatActivity {
}
- 4.2:组件跨模块调用
ARouter.getInstance().build("/gtest/test").navigation();
记住:如果注解没有指明group,arouter默认会以path的第一个节点gtest为组名进行分组
5.属性依赖注入
- 5.1:注解声明
@Route(path = "/test/activity1", name = "测试用 Activity")
public class Test1Activity extends BaseActivity {
@Autowired
int age = 10;
@Autowired
int height = 175;
@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;
@Autowired
TestObj obj;
@Autowired
List<TestObj> objList;
@Autowired
Map<String, List<TestObj>> map;
private long high;
@Autowired
String url;
@Autowired
HelloService helloService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test1);
ARouter.getInstance().inject(this);
}
}
- 5.2:注解跨模块调用
ARouter.getInstance().build("/test/activity1")
.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();
传入的Object需要使用Serializable序列化
public class TestSerializable implements Serializable {
public String name;
public int id;
public TestSerializable() {
}
public TestSerializable(String name, int id) {
this.name = name;
this.id = id;
}
}
注意点:
- 1.常用数据类型直接使用:Autowired注解即可
- 2.如果需要指定外部传入的数据key:可以使用name指定,如果这个字段是必须传入的,则需要指定required = true,外部未传入可能会报错
- 3.传入自定义类的属性则需要先对自定义进行序列化,且需要指定一个SerializationService:这个类是用于Object对象和json进行转化用
@Route(path = "/yourservicegroupname/json")
public class JsonServiceImpl implements SerializationService {
@Override
public void init(Context context) {
}
@Override
public <T> T json2Object(String text, Class<T> clazz) {
return JSON.parseObject(text, clazz);
}
@Override
public String object2Json(Object instance) {
return JSON.toJSONString(instance);
}
@Override
public <T> T parseObject(String input, Type clazz) {
return JSON.parseObject(input, clazz);
}
}
6.Service模块的调用
- 6.1:声明接口,其他组件通过接口来调用服务
public interface HelloService extends IProvider {
String sayHello(String name);
}
- 6.2:实现接口
@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) {
}
}
- 6.3:使用接口
6.3.1:使用依赖查找的方式发现服务,主动去发现服务并使用,下面两种方式分别是byName和byType
1.使用class类型查找
helloService3 = ARouter.getInstance().navigation(HelloService.class);
helloService3.sayHello("Vergil");
2.使用path查找
helloService4 = (HelloService) ARouter.getInstance().build("/yourservicegroupname/hello").navigation();
helloService4.sayHello("Vergil");
6.3.2:(推荐)使用依赖注入的方式发现服务,通过注解标注字段,即可使用,无需主动获取
@Autowired
HelloService helloService;
@Autowired(name = "/yourservicegroupname/hello")
HelloService helloService2;
helloService.sayHello("mikeaaaa");
helloService2.sayHello("mikeaaaa");
7.Fragment和BOARDCAST以及CONTENT_PROVIDER
使用方式和Activity类似,但是这三者都是直接获取对应的Class类对象,拿到对象后,可以操作对象,这里不再讲解
8.拦截器的使用
拦截器就是在跳转的过程中,设置的对跳转的检测和预处理等操作。
- 8.1:拦截器声明
可以添加拦截器的优先级,优先级越高,越优先执行
@Interceptor(priority = 7)
public class Test1Interceptor implements IInterceptor {
/**
* The operation of this interceptor.
*
* @param postcard meta
* @param callback cb
*/
@Override
public void process(final Postcard postcard, final InterceptorCallback callback) {
if ("/test/activity4".equals(postcard.getPath())) {
// 这里的弹窗仅做举例,代码写法不具有可参考价值
final AlertDialog.Builder ab = new AlertDialog.Builder(postcard.getContext());
ab.setCancelable(false);
ab.setTitle("温馨提醒");
ab.setMessage("想要跳转到Test4Activity么?(触发了\"/inter/test1\"拦截器,拦截了本次跳转)");
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);
}
});
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);
}
}
/**
* Do your init work in this method, it well be call when processor has been load.
*
* @param context ctx
*/
@Override
public void init(Context context) {
Log.e("testService", Test1Interceptor.class.getName() + " has init.");
}
}
可以设置绿色通道模式:greenChannel()不做拦截器处理
9.监听跳转状态
.navigation(this, new NavCallback() {
@Override
public void onArrival(Postcard postcard) {
Log.d("ARouter", "onArrival");
Log.d("ARouter", "成功跳转了");
}
@Override
public void onInterrupt(Postcard postcard) {
super.onInterrupt(postcard);
Log.d("ARouter", "被拦截了");
}
@Override
public void onFound(Postcard postcard) {
super.onFound(postcard);
Log.d("ARouter", "onFound:path:"+postcard.getPath());
Log.d("ARouter", "找到了对应的path");
}
@Override
public void onLost(Postcard postcard) {
super.onLost(postcard);
Log.d("ARouter", "onLost:path:"+postcard.getPath());
Log.d("ARouter", "没找到了对应的path");
}
});
10.自定义全局降级策略
// 实现DegradeService接口,并加上一个Path内容任意的注解即可
@Route(path = "/xxx/xxx")
public class DegradeServiceImpl implements DegradeService {
@Override
public void onLost(Context context, Postcard postcard) {
// do something.
}
@Override
public void init(Context context) {
}
}
11.动态注册路由信息
适用于部分插件化架构的App以及需要动态注册路由信息的场景,可以通过 ARouter 提供的接口实现动态注册 路由信息,
目标页面和服务可以不标注 @Route 注解,注意:同一批次仅允许相同 group 的路由信息注册
ARouter.getInstance().addRouteGroup(new IRouteGroup() {
@Override
public void loadInto(Map<String, RouteMeta> atlas) {
atlas.put("/dynamic/activity", // path
RouteMeta.build(
RouteType.ACTIVITY, // 路由信息
TestDynamicActivity.class, // 目标的 Class
"/dynamic/activity", // Path
"dynamic", // Group, 尽量保持和 path 的第一段相同
0, // 优先级,暂未使用
0 // Extra,用于给页面打标
)
);
}
});
12:使用自己的日志工具打印日志
ARouter.setLogger();
13.使用自己提供的线程池
ARouter.setExecutor();
14.重写跳转URL
// 实现PathReplaceService接口,并加上一个Path内容任意的注解即可
@Route(path = "/xxx/xxx") // 必须标明注解
public class PathReplaceServiceImpl implements PathReplaceService {
/**
* For normal path.
*
* @param path raw path
*/
String forString(String path) {
return path; // 按照一定的规则处理之后返回处理后的结果
}
/**
* For uri type.
*
* @param uri raw uri
*/
Uri forUri(Uri uri) {
return url; // 按照一定的规则处理之后返回处理后的结果
}
}
15.使用agp插件动态路由表加载
- 1.在项目级build.gradle中:
buildscript {
dependencies {
classpath "com.alibaba:arouter-register:$arouter_register_version"
}
}
- 2.在模块级app下引入路由表自动加载插件
id 'com.alibaba.arouter'
同步代码后,在编译期会自动进行路由表的加载,可以加快arouter的第一次初始化时间,为什么是第一次呢,因为arouter初始化会缓存路由表信息到文件中。
Q&A
1."W/ARouter::: ARouter::No postcard![ ]"
这个Log正常的情况下也会打印出来,如果您的代码中没有实现DegradeService和PathReplaceService的话,因为ARouter本身的一些功能也依赖 自己提供的Service管理功能,ARouter在跳转的时候会尝试寻找用户实现的PathReplaceService,用于对路径进行重写(可选功能),所以如果您没有 实现这个服务的话,也会抛出这个日志
推荐在app中实现DegradeService、PathReplaceService
2."W/ARouter::: ARouter::There is no route match the path [/xxx/xxx], in group xxx"
通常来说这种情况是没有找到目标页面,目标不存在
如果这个页面是存在的,那么您可以按照下面的步骤进行排查
- a.检查目标页面的注解是否配置正确,正确的注解形式应该是 (@Route(path="/test/test"), 如没有特殊需求,请勿指定group字段,废弃功能)
- b.检查目标页面所在的模块的gradle脚本中是否依赖了 arouter-compiler sdk (需要注意的是,要使用apt依赖,而不是compile关键字依赖)
- c.检查编译打包日志,是否出现了形如 ARouter::?Compiler >>> xxxxx 的日志,日志中会打印出发现的路由目标
- d.启动App的时候,开启debug、log(openDebug/openLog), 查看映射表是否已经被扫描出来,形如 D/ARouter::: LogisticsCenter has already been loaded, GroupIndex[4],GroupIndex > 0
3.开启InstantRun之后无法跳转(高版本Gradle插件下无法跳转)?
因为开启InstantRun之后,很多类文件不会放在原本的dex中,需要单独去加载,ARouter默认不会去加载这些文件,因为安全原因,只有在开启了openDebug之后 ARouter才回去加载InstantRun产生的文件,所以在以上的情况下,需要在init之前调用openDebug
4.TransformException:java.util.zip.ZipException: duplicate entry ....
ARouter有按组加载的机制,关于分组可以参考 6-1 部分,ARouter允许一个module中存在多个分组,但是不允许多个module中存在相同的分组,会导致映射文件冲突
5.Kotlin类中的字段无法注入如何解决?
首先,Kotlin中的字段是可以自动注入的,但是注入代码为了减少反射,使用的字段赋值的方式来注入的,Kotlin默认会生成set/get方法,并把属性设置为private 所以只要保证Kotlin中字段可见性不是private即可,简单解决可以在字段上添加 @JvmField
6.通过URL跳转之后,在intent中拿不到参数如何解决?
需要注意的是,如果不使用自动注入,那么可以不写 ARouter.getInstance().inject(this),但是需要取值的字段仍然需要标上 @Autowired 注解,因为 只有标上注解之后,ARouter才能知道以哪一种数据类型提取URL中的参数并放入Intent中,这样您才能在intent中获取到对应的参数
7.新增页面之后,无法跳转?
ARouter加载Dex中的映射文件会有一定耗时,所以ARouter会缓存映射文件,直到新版本升级(版本号或者versionCode变化),而如果是开发版本(ARouter.openDebug()), ARouter 每次启动都会重新加载映射文件,开发阶段一定要打开 Debug 功能
相关推荐
- 从头再来,再见了我曾奋斗的地方
-
今天,我告别了奋斗二十年的地,就现在也不敢相信曾经是那么的辉煌那么让我骄傲的厂子今天确是也要告别了,我们不知道该怨谁该谁买单可苦的是我们还得从头再来...
- 《万古神帝》第4202章(评)咬定神树不放松,第二儒祖仍在破局中
-
各位老铁,酒窝突然有了一个匪夷所思的猜想,从突袭天庭,再到夺取世界树,到天姥和若尘打上天界对战第二儒祖和慕容主宰。这一切会不会只是时空人祖一开始就谋划好的,引蛇出洞之计?第二儒祖乃至整个神界也只不过是...
- 香皂和透明皂可以混用吗?
-
香皂和透明皂是家庭常用物品,使用频率比较高。但是,有些市民认为香皂比较柔和,香味也比较好,因此喜欢用香皂给孩子洗衣服。而有些成年人,特别是男性,觉得透明皂的去污能力强,有时候会使用透明皂洗手或洗澡。那...
- 批评别人的技巧
-
批评和赞美是一对反义词,但在说话这门艺术里,两者不过是两种与人交流沟通的不同方式而已,赞美侧重于一个人的优点和长处,批评侧重于一个人的缺点和不足。赞美人需要讲究方式和技巧,批评人同样不能草率从事。批评...
- 山东2020春季高考技能考试主考学校及考试安排来了
-
山东2020年春季高考技能考试安排在7月14日—20日进行,各类别具体考试时间由主考学校自主确定。考生请于7月11日起登录山东省教育招生考试院招生考试信息平台(http://wsbm.sdzk.cn)...
- 石河子大学2019-2020学年第二学期选课通知
-
它来了,它来了小石带着秘籍来了!又快到了每学期的选课时间内心是不是既兴奋又紧张敲黑板,划重点!为保证选课工作的顺利进行现将选课事宜安排如下你想要的课程安排选课时间及其相关要求...
- “奋进新时代”主题成就展线上开展!一起为山西单元云端打call
-
登录网址,点击按钮,“祝融号”火星车模型、天问一号着陆器模型、东风-17高超音速导弹等实物展品立刻呈现;跟随着语音讲解,奋进山西单元的精彩内容就跃然眼前……近日,“奋进新时代”主题成就展网上展馆上线。...
- 延边大学关于2021年秋季学期本(专)科教学运行工作安排的通知
-
关于2021年秋季学期本(专)科教学运行工作安排的通知根据学校《关于2021年秋季学期师生返校安排的通知》和《关于2021级新生报到相关事宜的通知》,为做好2021年秋季学期开学期间的本(专)科教学相...
- 阿里巴巴Yun OS智能手表Pay Watch亮相:深度整合支付宝
-
IT之家讯9月22日消息,刚刚我们报道了阿里巴巴智能手表亮相YunOS官网,本来以为阿里巴巴会重点介绍一下这款产品。没想到这款智能手表已经悄悄的登录淘宝众筹了。与此同时,它的名字也正式揭晓:Pay...
- 内网本机IP怎么查?外网本机IP地址查询方法
-
在工作中,我们或许要查看本机的ip地址,不是很懂电脑的人,对此可能会无从下手,今天飞飞就给你们分享外网/内网本机IP地址查询方法,感兴趣的往下看,非常简单,肯定可以学会...
- 查完成绩,你是不是还需要了解一下这个「奸笑脸」
-
各位假期生活过得如何?不管你是在各个城市享受旅行,或是已经摊在家里过着肥宅的快乐生活。都醒一醒吧!这一次不同于各种校园推送里的假消息是真的可以查成绩了!成绩已于今日上午...
- 「鼠标」垂直鼠标再体验:多彩DELUX 90度垂直鼠 M618与M618PLUS
-
我因为用原来的鼠标时间比较久了,想换个姿势用鼠标。我仔细搜了一下,垂直鼠标,只找到罗技的MXVERTICAL和多彩的M618系列产品。因为我的初体验是罗技的MXVERTICAL,所以这篇叫“垂直...
- 说一个目前最让你焦虑的事?
-
来说说那些让你感到非常焦虑但是不被生活中你的亲人朋友所知道的吧,在这里说一下,写下来,聊一聊,互相温暖鼓励一下吧!...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- mybatis plus (70)
- scheduledtask (71)
- css滚动条 (60)
- java学生成绩管理系统 (59)
- 结构体数组 (69)
- databasemetadata (64)
- javastatic (68)
- jsp实用教程 (53)
- fontawesome (57)
- widget开发 (57)
- vb net教程 (62)
- hibernate 教程 (63)
- case语句 (57)
- svn连接 (74)
- directoryindex (69)
- session timeout (58)
- textbox换行 (67)
- extension_dir (64)
- linearlayout (58)
- vba高级教程 (75)
- iframe用法 (58)
- sqlparameter (59)
- trim函数 (59)
- flex布局 (63)
- contextloaderlistener (56)