一.简介
在Android的组件化中,组件之间的通信框架有很多,比如阿里的开源框架ARouter。AutoService是谷歌提供的用户组件间通信的框架。
优点
1.提高代码可读性:通过注解明确标记出哪些类是服务的提供者,使得代码更易于理解。
2.提高开发效率:自动化的过程减少了人为错误,提高了开发效率。
缺点:
AutoService 只能用于生成 Java SPI 的配置文件,对于其他类型的文件生成没有支持。
二.代码讲解
Gradle依赖
kapt "com.google.auto.service:auto-service:1.0.1"
implementation "com.google.auto.service:auto-service:1.0.1"
接口
public interface IAutoService extends Serializable {
default String autoServiceTest(String title) {
return "我是AutoService测试 " + title;
}
}
接口实现
@AutoService(IAutoService::class)
class AutoServiceImpl : IAutoService {
override fun autoServiceTest(title: String): String {
return super.autoServiceTest(title)
}
}
调用
TextView textView = findViewById(R.id.content);
String result = "";
IAutoService service = getAutoService(IAutoService.class);
if (null != service) result = service.autoServiceTest("0716");
textView.setText(result);
private <T> T getAutoService(Class<T> tClass) {
ServiceLoader<T> impl = ServiceLoader.load(tClass);
Iterator<T> iterator = impl.iterator();
T service = null;
while (iterator.hasNext()) {
service = iterator.next();
}
if (null == service) {
Log.d("AutoService", tClass.getName() + "未注册");
return null;
}
Log.d("AutoService", "tClass:" + tClass.getName());
return service;
}
结果
tClass:com.example.newdemo.auto_service.IAutoService
三.原理
AutoService 会在构建时创建需要的依赖配置, 目录META-INF/services 如下
拿到这个接口,就可以实现调用了。