创建 router-runtime 运行时工程
主工程引入 router-runtime
新建 Router.kt 存储所有映射表信息
object Router {
private const val TAG = "RouterTAG"
// 编译期间生成的总映射表
private const val GENERATED_MAPPING =
"com.imooc.router.mapping.generated.RouterMapping"
// 存储所有映射表信息
private val mapping : HashMap = HashMap()
// 初始化:获取RouterMapping中所有的路由信息
fun init(){
try{
val clazz = Class.forName(GENERATED_MAPPING)
val method = clazz.getMethod("get")
val allMaping = method.invoke(null) as Map
if(allMaping?.size > 0){
allMaping.onEach {
Log.i(TAG,"${it.key} -> ${it.value}")
}
mapping.putAll(allMaping)
}
}catch (e:Throwable){
}
}
// 跳转页面:封装参数
fun go(context: Context, url:String){
if (context == null || url == null){
Log.i(TAG,"go: param error.")
return
}
// 匹配URL,找到目标页面
// router://imooc/profile?name=imooc&message=hello
val uri = Uri.parse(url)
val scheme = uri.scheme
val host = uri.host
val path = uri.path
var targetActivityClass = ""
mapping.onEach {
val ruri = Uri.parse(it.key)
val rscheme = ruri.scheme
val rhost = ruri.host
val rpath = ruri.path
if(rscheme == scheme && rhost == host && rpath == path){
targetActivityClass = it.value
}
}
if(targetActivityClass == ""){
Log.e(TAG,"go: no destination found.")
return
}
// 解析URL里面的参数,封装成为一个Bundle
val bundle = Bundle()
val query = uri.query
query?.let {
if(it.length >= 3){
val args = it.split("&")
args.onEach { arg->
val splits = arg.split("=")
bundle.putString(splits[0],splits[1])
}
}
}
// 打开对应的Activity,并传入参数
try {
val activity = Class.forName(targetActivityClass)
val intent = Intent(context,activity)
intent.putExtras(bundle)
context.startActivity(intent)
}catch (e:Throwable){
Log.e(TAG,"go : error while start activity: $targetActivityClass, e = $e")
}
}
}
主工程新建 App Application,在onCreate 方法初始化 Router
class App:Application() {
override fun onCreate() {
super.onCreate()
Router.init()
}
}
实现页面跳转
@Destination(
url = "router://page-login",
description = "登录"
)
public class LoginActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView routerBundle = findViewById(R.id.tv_router);
// 解析传递的参数
Bundle extras = getIntent().getExtras();
if(extras!=null){
Set keys =
extras.keySet();
if (keys!=null && keys.size()>0){
String value = extras.getString(keys.iterator().next());
routerBundle.setText(value);
}
}
}
}
String url = "router://page-login?name=imooc&message=hello"
Router.INSTANCE
.go(v.getContext(),url);
发布 router-runtime 到本地maven
build.gradle
// 应用发布功能
apply from : rootProject.file('maven-publish.gradle')
执行命令 gradle :router-runtime:uploadArchive 发布maven



