TheRouter可以成为你在应用中进行模块化开发、组件间通信和路由导航的有力工具。以下是一份简单的使用TheRouter的指南:
步骤 1: 添加依赖
在你的应用模块的 build.gradle 文件中添加TheRouter的依赖:
gradle
Copy code
implementation ‘cn.therouter:router-runtime:1.1.4’
kapt ‘cn.therouter:apt:1.1.4’
注意: 如果你要使用KSP(Kotlin Symbol Processing)代替KAPT,可以参考前面的内容进行配置。
步骤 2: 初始化TheRouter
在你的应用的 Application 类的 onCreate 方法中初始化TheRouter:
kotlin
Copy code
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
TheRouter.init(this)
}
}
步骤 3: 声明页面
在每个需要路由导航的页面(Activity、Fragment等)上使用 @Route 注解进行声明:
kotlin
Copy code
@Route(“app://main”)
class MainActivity : AppCompatActivity() {
// …
}
步骤 4: 导航到页面
在你的应用中,可以使用以下代码导航到声明的页面:
kotlin
Copy code
TheRouter.build(“app://main”).navigation()
步骤 5: 传递参数
你可以使用 withXXX 方法来传递参数:
kotlin
Copy code
TheRouter.build(“app://details”)
.withInt(“product_id”, 123)
.withString(“product_name”, “Awesome Product”)
.navigation()
在目标页面中,可以通过 TheRouter.getParamXXX 方法获取传递过来的参数:
kotlin
Copy code
val productId = TheRouter.getParamInt(“product_id”, 0)
val productName = TheRouter.getParamString(“product_name”, “”)
步骤 6: 使用Interceptor
你可以使用 Interceptor 对路由进行拦截和处理:
kotlin
Copy code
TheRouter.build(“app://main”)
.addInterceptor(object : RouteInterceptor {
override fun intercept(chain: RouteInterceptor.Chain) {
// 在这里处理拦截逻辑,例如登录检查
if (userIsLoggedIn()) {
chain.proceed() // 继续路由
} else {
// 跳转到登录页面
TheRouter.build(“app://login”).navigation()
}
}
})
.navigation()
其他功能:
服务提供方: TheRouter提供了服务提供方功能,可以方便地在不同模块之间提供和获取服务。
Action管理: 通过Action进行全局系统回调,用于预埋一系列操作,如弹窗、上传日志、清理缓存等。
FlowTask: 用于模块的独立初始化、懒加载初始化、编译期循环引用检测等。
多进程支持: TheRouter支持多进程,可以在主进程外执行初始化逻辑。
自定义Log输出: 可以自定义Log输出,方便调试和线上日志采集。
这只是TheRouter的基础用法,还有很多高级功能可以在项目需要时逐步学习和应用。参考TheRouter的文档和示例项目,可以更好地理解和使用TheRouter:TheRouter文档