### Custom Route Map Initialization Task Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/Navigator Implement a custom InitTask to handle route map initialization, especially when dynamic remote updates are used. This example shows how to fetch a remote route map and fall back to the internal one if fetching fails. This code must be called before Application.super.onCreate(). ```java RouteMap.setInitTask(new RouterMapInitTask() { /** * 此方法执行在异步 */ @Override public void asyncInitRouteMap() { // 此处为纯业务逻辑,每家公司远端配置方案可能都不一样 // 不建议每次都请求网络,否则请求网络的过程中,路由表是空的,可能造成APP无法跳转页面 // 最好是优先加载本地,然后开异步线程加载远端配置 String json = Connfig.doHttp("routeMap"); // 建议加一个判断,如果远端配置拉取失败,使用包内配置做兜底方案,否则可能造成路由表异常 if (!TextUtils.isEmpty(json)) { List list = new Gson().fromJson(json, new TypeToken>() { }.getType()); // 建议远端下发路由表差异部分,用远端包覆盖本地更合理 RouteMap.addRouteMap(list); } else { // 在异步执行TheRouter内部兜底路由表 initRouteMap() } } }); ``` -------------------------------- ### Delay Page Navigation Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/Navigator Use the .padding() method to temporarily store a navigation action. This is useful for initializing large route tables or when the app is in the background and cannot immediately start an Activity (Android 8.0+). The pending navigation can be resumed later. ```java // 暂存的动作可以有多个,会在恢复时按顺序执行 TheRouter.build("http://therouter.com/home") .withInt("key1", 12345678) .padding()// 暂存当前跳转动作 .navigation(context); // 恢复 sendPendingNavigator(); //toplevel方法,无需类名调用,Java请通过NavigatorKt类名调用 ``` -------------------------------- ### Implement Router Replace Interceptor Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/Navigator Use RouterReplaceInterceptor to replace a RouteItem with another before navigation, for example, redirecting to a login page if a user is underage. This interceptor acts after the route is found in the table. It must be added before TheRouter.build().navigation(). ```java Navigator.addRouterReplaceInterceptor(new RouterReplaceInterceptor() { @Override public RouteItem replace(RouteItem routeItem) { if (user.age() < 18 && routeItem.getClassName().contains("ChildrenProhibitActivity")) { RouteItem target = new RouteItem(); target.setClassName(HomeActivity.class.getName()); String[] path = {"https://kymjs.com/too/young"}; target.setPathArray(path); target.setDescription("也可以在这里修改原有路由的参数信息"); return target; } return routeItem; } }); ``` -------------------------------- ### Define Route and Navigate with Parameters Source: https://github.com/huolalatech/hll-wp-therouter-android/blob/dev/README.md Annotate your Activity with @Route to define its path, action, description, and parameters. Use TheRouter.build() to construct navigation requests with various data types. ```java @Route(path = "http://therouter.com/home", action = "action://scheme.com", description = "second page", params = {"hello", "world"}) public class HomeActivity extends BaseActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); TheRouter.build("Path") .withInt("intValue", 12345678) .withString("str_123_Value", "传中文字符串") .withBoolean("boolValue", true) .withLong("longValue", 123456789012345L) .withChar("charValue", 'c') .withDouble("double", 3.14159265358972) .withFloat("floatValue", 3.14159265358972F) .navigation(); } } ``` -------------------------------- ### Configure TheRouter Gradle Plugin and Dependencies Source: https://github.com/huolalatech/hll-wp-therouter-android/blob/dev/README.md Add the plugin to your root build.gradle and apply it in your app module. Include the necessary kapt and implementation dependencies for TheRouter. ```gradle // root build.gradle classpath 'cn.therouter:plugin:1.3.2' // app module apply plugin: 'therouter' // dependencies kapt "cn.therouter:apt:1.3.2" implementation "cn.therouter:router:1.3.2" ``` -------------------------------- ### Perform Page Navigation with Parameters Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/Navigator Navigate to a page using TheRouter.build() and pass various types of parameters, including primitives, Serializable, Parcelable, and arbitrary objects. The navigation can be initiated with or without a request code for startActivityForResult. ```java // 传入参数可以通过注解 @Autowired 解析成任意类型,如果是对象建议传json // context 参数如果不传或传 null,会自动使用 application 替换 TheRouter.build("http://therouter.com/home") .withInt("key1", 12345678) .withString("key2", "参数") .withBoolean("key3", false) .withSerializable("key4", object) .withObject("object", any) // 与上一个方法不同,这个方法可以传递任意对象,但是接收的地方对象类型请保证一致 .navigation(context); // 如果传入 requestCode,默认使用startActivityForResult启动Activity .navigation(context, 123); // 如果要打开的是fragment,需要使用 .createFragment(); ``` -------------------------------- ### Custom Business Node Initialization Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/FlowTaskExecutor Define custom initialization tasks in Kotlin, such as initializing the recording SDK after a privacy agreement task ('AgreePrivacyCache') is completed. The task is triggered by calling TheRouter.runTask(). ```kotlin // 假设隐私协议任务名为:AgreePrivacyCache /** * 同意隐私协议后初始化录音SDK */ @FlowTask(taskName="initRecord", dependsOn="AgreePrivacyCache") fun init(context:Context) = initRecordAudioSDK() // 当用户同意隐私协议时,调度依赖隐私协议的所有任务执行 TheRouter.runTask("AgreePrivacyCache") ``` -------------------------------- ### Declare Immediate Module Initialization Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/FlowTaskExecutor Annotate a static Java method with @FlowTask for immediate execution on the main thread during application startup. The taskName must be globally unique. ```java @FlowTask(taskName = "app1") public static void test3(Context context) { System.out.println("main线程=========应用启动就会执行"); } ``` -------------------------------- ### Declare Asynchronous Module Initialization Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/FlowTaskExecutor Annotate a static Java method with @FlowTask to execute initialization asynchronously after Application.onCreate(). Specify dependencies using dependsOn. ```java /** * 将会在异步执行 */ @FlowTask(taskName = "mmkv_init", dependsOn = TheRouterFlowTask.APP_ONCREATE, async = true) public static void test2(Context context) { System.out.println("异步=========Application onCreate后执行"); } ``` -------------------------------- ### Auto-receive route parameters with annotations Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/Navigator Use annotations to automatically receive String and basic data types as route parameters. Ensure TheRouter.inject(this) is called, preferably in a base class. ```java @Route(path = "http://therouter.com/home") public class HomeActivity extends BaseActivity { // 允许解析成8种基本数据类型或对应封装类 @Autowired int key1; // String类型可以自动解析,除了String和8种基本类型封装类以外, // 其他的Object需要自定义解析规则,自定义方式见下文高级功能介绍 2.3 节内容 @Autowired String key2; // 如果没有声明 name,则使用变量名作为 Intent 解析的key @Autowired(name = "key3") String user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 使用注解接收对象时,必须调用这一句,建议直接在 Base 中统一调用。 TheRouter.inject(this); // 当然如果不嫌麻烦,也是允许自己手动解析的,但是只能解析成String,因为传的时候都是以String类型传递 String key1 = activity.getIntent().getStringExtra("key1"); } } ``` -------------------------------- ### Add Third-Party Library Route Item Programmatically Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/Navigator Dynamically add a route item for a third-party library's Activity or Fragment at runtime. This method requires the route path, the fully qualified class name of the component, an optional action, and a description. ```kotlin addRouteItem(RouteItem(path, className, action, description)) ``` -------------------------------- ### Proguard Rules for Fragment Routing Source: https://github.com/huolalatech/hll-wp-therouter-android/blob/dev/README.md Include these proguard rules if you are using TheRouter for fragment page routing to prevent them from being stripped during code shrinking. ```proguard # need add for Fragment page route # -keep public class * extends android.app.Fragment # -keep public class * extends androidx.fragment.app.Fragment ``` -------------------------------- ### Initialize TheRouter Debug Mode Source: https://github.com/huolalatech/hll-wp-therouter-android/blob/dev/README.md Set the debug mode for TheRouter within your application's base context. This is recommended for viewing log information during development. ```java @Override protected void attachBaseContext(Context base) { TheRouter.setDebug(true or false); super.attachBaseContext(base); } ``` -------------------------------- ### Execute an Action in Kotlin Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/ActionManager Execute a declared action using TheRouter.build(). If the action is not declared, no operation will occur. This is the standard way to trigger predefined actions within the system. ```kotlin const val ACTION = "therouter://action/xxx" // 如果执行了一个没有被声明的Action,则不会有任何动作 TheRouter.build(ACTION).action() ``` -------------------------------- ### Pass and receive object parameters Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/Navigator Pass arbitrary objects using withObject and ensure the receiving end uses the same object type. TheRouter.inject(this) must be called to receive objects via annotations. ```java TheRouter.build("http://therouter.com/home") .withString("user_info_object", json) // 传递json对象 .withObject("user_object", any) // 这个方法可以传递任意对象,但是接收的地方对象类型请保证一致 .navigation(context); @Route(path = "http://therouter.com/home") public class HomeActivity extends BaseActivity { @Autowired User user_info_object; @Autowired User user_object; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 使用注解接收对象时,必须调用这一句,建议直接在 Base 中统一调用。 TheRouter.inject(this); } } ``` -------------------------------- ### Set Default Navigation Callback Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/Navigator Define a global callback to handle navigation events. This callback is invoked after the Activity is created, immediately after startActivity, and when a route is found or lost. It does not apply if the destination is a Fragment. ```java NavigatorKt.defaultNavigationCallback(new NavigationCallback() { // 落地页Activity打开后,执行到onCreate会回调 @Override public void onActivityCreated(@NonNull Navigator navigator, @NonNull Activity activity) { super.onActivityCreated(navigator, activity); } // startActivity执行后会立刻回调 @Override public void onArrival(@NonNull Navigator navigator) { super.onArrival(navigator); } // 找到待跳转的落地页时就会回调(startActivity之前) @Override public void onFound(@NonNull Navigator navigator) { super.onFound(navigator); } // 找不到落地页的时候会回调 @Override public void onLost(@NonNull Navigator navigator) { super.onLost(navigator); } }); ``` -------------------------------- ### Declare Dependent Module Initialization Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/FlowTaskExecutor Annotate a static Java method with @FlowTask to execute initialization on the main thread only after specified dependent tasks (e.g., 'mmkv', 'app1') have completed. ```java /** * 将会在主线程初始化 */ @FlowTask(taskName = "test", dependsOn = "mmkv,app1") public static void test3(Context context) { System.out.println("main线程=========在app1和mmkv两个任务都执行以后才会被执行"); } ``` -------------------------------- ### Inject Page Parameters with TheRouter Source: https://github.com/huolalatech/hll-wp-therouter-android/blob/dev/README.md Call TheRouter.inject(this) in the onCreate() method of your Activity or Fragment to enable automatic parameter injection. It's recommended to do this in a base class. ```java @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); TheRouter.inject(this); } ``` -------------------------------- ### ProGuard Rules for TheRouter Source: https://github.com/huolalatech/hll-wp-therouter-android/blob/dev/README.md These ProGuard rules are necessary to ensure that TheRouter components are not removed or obfuscated during the release build process. Include these in your ProGuard configuration file. ```proguard -keep public class * extends android.support.v4.app.Fragment -keep class androidx.annotation.Keep -keep @androidx.annotation.Keep class * {*}; -keepclassmembers class * { @androidx.annotation.Keep *; } -keepclasseswithmembers class * { @androidx.annotation.Keep ; } -keepclasseswithmembers class * { @androidx.annotation.Keep ; } -keepclasseswithmembers class * { @androidx.annotation.Keep (...); } -keepclasseswithmembers class * { @com.therouter.router.Autowired ; } ``` -------------------------------- ### Declare an ActionInterceptor in Kotlin Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/ActionManager Declare an ActionInterceptor to handle a specific action. Ensure the action URI follows a consistent format. This interceptor will be invoked when the action is triggered. ```kotlin const val ACTION = "therouter://action/xxx" @FlowTask(taskName="action_demo") fun init(context: Context) = TheRouter.addActionInterceptor(ACTION, object: ActionInterceptor() { override fun handle(context: Context, args: Bundle): Boolean { // do something return false } }) ``` -------------------------------- ### Set Global Router Interceptor (AOP) Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/Navigator Use setRouterInterceptor to set a single global interceptor for AOP-like behavior during the entire navigation process. This allows custom logic before, during, or after navigation, such as blocking debug activities in production. The callback object can also be customized. ```java Navigator.setRouterInterceptor(new RouterInterceptor() { @Override public void process(RouteItem routeItem, InterceptorCallback callback) { if (!TheRouter.isDebug() && routeItem.getClassName().equals("com.kymjs.DebugActivity")) { return; } else { // callback 对象也是可以自定义的,看你怎么用了 callback.onContinue(routeItem); } } }); ``` -------------------------------- ### Implement Navigator Path Fixer Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/Navigator Use NavigatorPathFixHandle to modify route paths before navigation, such as converting relative paths to absolute or ensuring correct URL schemes. This must be added before TheRouter.build(). ```java Navigator.addNavigatorPathFixHandle(new NavigatorPathFixHandle() { @Override public String fix(String path) { path = path.replace("http://", "https://"); if (!path.contains("www.kymjs.com") && path.startsWith("/")) { path = "https://www.kymjs.com" + path; } return path; } /** * 数字越大,优先级越高, * 优先级方法通常情况下不需要重写,除非你真的有什么特殊场景会用到 */ @Override public int getPriority() { return 5; } }); ``` -------------------------------- ### Implement Path Replace Interceptor Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/Navigator Use PathReplaceInterceptor to replace specific route paths with new ones during navigation. This is useful for modularization or fixing specific links. It must be added before TheRouter.build().navigation(). ```java Navigator.addPathReplaceInterceptor(new PathReplaceInterceptor() { @Override public String replace(String path) { if ("https://kymjs.com/splash/to/home".equals(path)) { return "https://kymjs.com/business/home"; } return path; } }); ``` -------------------------------- ### Check if URL is a Route Path Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/Navigator Determine if a given URL corresponds to a defined route path in the router map. Returns null if the URL is not a recognized route. ```kotlin // kotlin toplevel方法,Java调用请使用RouteMapKt类 matchRouteMap("url填这里") == null ``` -------------------------------- ### ActionInterceptor Priority in Kotlin Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/ActionManager Define the priority for an ActionInterceptor. Higher numerical values indicate higher priority. This allows for ordered execution and interruption of lower-priority interceptors. ```kotlin abstract class ActionInterceptor { abstract fun handle(context: Context, args: Bundle): Boolean fun onFinish() {} /** * 数字越大,优先级越高 */ open val priority: Int get() = 5 } ``` -------------------------------- ### Declare Route Item with @Route Annotation Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/Navigator Use the @Route annotation to declare a route item for an Activity or Fragment. This allows the page to be opened via routing. Multiple route items can be declared for a single page. ```java @Route(path = "http://therouter.com/home", action = "action://scheme.com", description = "第二个页面", params = {"hello", "world"}) public class HomeActivity extends AppCompatActivity { } ``` -------------------------------- ### Add custom Autowired parser Source: https://github.com/huolalatech/hll-wp-therouter-android/wiki/Navigator Register a custom parser for @Autowired annotations to handle custom object deserialization from JSON. This is useful for complex object types. ```java TheRouter.addAutowiredParser(new MyAutowiredParser()); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.