添加jitpack仓库
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
添加依赖:
dependencies {
//kotlin 使用kapt编译时依赖注解,Java使用annotationProcessor
kapt 'com.github.roger1245.XRouter:xrouter-compiler:1.0.2'
api 'com.github.roger1245.XRouter:xrouter-core:1.0.2'
}
添加配置:
android {
defaultConfig {
...
javaCompileOptions {
annotationProcessorOptions {
arguments = [moduleName: project.getName()]
}
}
}
初始化SDK:
public class XRouterApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
XRouter.Companion.init(this);
}
}
添加注解:
@Route(path = Config.Module1Activity)
class Module1Activity : AppCompatActivity() {
...
}
发起路由操作:
//1.路由内通过path跳转另一个Activity
XRouter.sInstance.build(Config.Module1Activity).navigation()
通过aop方式获取服务
val hello: HelloService = XRouter.sInstance.build(Config.HELLO_SERVICE).navigation() as HelloService
hello.sayHello(this)
//实现接口
@Route(path = Config.HELLO_SERVICE)
public class HelloService implements IProvider {
@Override
public void init(Context context) {
Toast.makeText(context, "HelloService init successfully", Toast.LENGTH_SHORT).show();
}
public void sayHello(Context context) {
Toast.makeText(context, "HelloService: Hello", Toast.LENGTH_SHORT).show();
}
}
通过接口的方式发现服务:
val userService: IUserService? = XRouter.sInstance.navigation(IUserService::class.java)
userService?.login(this)
//实现接口
@Route(path = Config.USER_SERVICE_IMPL)
public class UserServiceImpl implements IUserService {
@Override
public void init(Context context) {
Toast.makeText(context, "UserServiceImpl init successfully", Toast.LENGTH_SHORT).show();
}
@Override
public void login(Context context) {
Toast.makeText(context, "UserServiceImpl login successfully", Toast.LENGTH_SHORT).show();
}
}
//实现IProvider接口
public interface IUserService extends IProvider {
public void login(Context context);
}
为了加快第一次进入应用的速度,可以通过gradle插件的方式利用ASM插入字节码,替代原来的运行时反射查找类文件的方式,如何引入:
根build.gradle引入:
buildscript {
...
dependencies {
....
classpath "com.github.roger1245.XRouter:xrouter-gradle-plugin:latestversion"
}
}
项目build.gradle引入:
apply plugin: 'xrouter'
即可。