TheRouter Android Documentation

repository·dev·Indexed 23 days ago

https://github.com/huolalatech/hll-wp-therouter-android

An Android componentization solution for page navigation, cross-module dependency injection, automatic module initialization, and dynamic remote method loading. It features a fluent API for navigating to @Route annotated pages with type-safe parameter passing, automatic initialization via FlowTaskExecutor, and tools for migrating from other routing frameworks.

Tokens
2.5K
Snippets
7
Records
12
Agent score
80%

What's inside TheRouter

  1. Initialize TheRouter and set Debug mode

    dev

    TheRouter features automatic initialization, so no explicit initialization code is required. However, it is recommended to set the debug environment in your Application.attachBaseContext() method as early as possible to enable log information.

    @Override
    protected void attachBaseContext(Context base) {
        TheRouter.setDebug(true or false);
        super.attachBaseContext(base);
    }
  2. Install TheRouter via Gradle

    dev

    To use TheRouter in your Android project, configure your Gradle files as follows:

    1. In your root build.gradle, add the TheRouter plugin to the classpath.
    2. In your app module build.gradle, apply the therouter plugin.
    3. Add the apt, router, and plugin dependencies to your module's dependencies block.

    Note: Ensure you use the correct versions (currently 1.3.2).

    // 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"
  3. Configure ProGuard rules for TheRouter

    dev

    To prevent class name obfuscation and ensure proper routing (especially for Fragments) and dependency injection, add the following rules to your ProGuard configuration:

    Important: If using Fragment routing, you must ensure Fragment classes are not obfuscated.

    # If using Fragment routing, ensure class names are not obfuscated
    # -keep public class * extends android.app.Fragment
    # -keep public class * extends androidx.fragment.app.Fragment
    # -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 <methods>;
    }
    -keepclasseswithmembers class * {
        @androidx.annotation.Keep <fields>;
    }
    -keepclasseswithmembers class * {
        @androidx.annotation.Keep <init>(...);
    }
    -keepclasseswithmembers class * {
        @com.therouter.router.Autowired <fields>;
    }
  4. Understand the RouteItem data model

    dev

    A RouteItem represents a single entry in the routing table. It maps a unique path to a specific target className (the landing page) and an optional action to be performed upon arrival.

    Key properties include:

    • path: The unique route identifier (e.g., /user/profile).
    • className: The fully qualified name of the class to be instantiated.
    • action: An instruction for what the target page should do after navigation.
    • description: A developer-facing comment describing the route.
    • extras: A Bundle containing runtime parameters used during navigation.

    RouteItem is both Parcelable and Serializable, allowing it to be passed between Android components.

  5. Navigate to a Page with Parameters

    dev

    Use the TheRouter.build("path") API to initiate navigation. You can chain multiple .withX(...) methods to pass different data types (Int, String, Boolean, Long, Char, Double, Float) to the destination. Finally, call .navigation() to execute the transition.

    Destination pages must be annotated with @Route to be discoverable by the router.

    @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();
        }
    }
  6. Inject Page Parameters in Activity or Fragment

    dev

    To enable parameter injection (receiving data passed via navigation), call TheRouter.inject(this) inside the onCreate() method of your Activity or Fragment. It is recommended to implement this in a BaseActivity or BaseFragment to ensure all pages are covered.

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TheRouter.inject(this);
    }
  7. Navigate to a page using TheRouter

    dev

    Use the @Route annotation to define a path for your Activity or Fragment. To perform navigation, use TheRouter.build("target_path") followed by type-specific with... methods to pass data, and finally call .navigation().

    @Route(path = "http://therouter.com/home", action = "action://scheme.com",
            description = "第二个页面", params = {"hello", "world"})
    public class HomeActivity extends BaseActivity {
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            TheRouter.build("要跳转的目标页Path")
                .withInt("intValue", 12345678) // Pass int
                .withString("str_123_Value", "传中文字符串") // Pass string
                .withBoolean("boolValue", true)
                .withLong("longValue", 123456789012345L)
                .withChar("charValue", 'c')
                .withDouble("double", 3.14159265358972)
                .withFloat("floatValue", 3.14159265358972F)
                .navigation();
        }
    }
  8. Configure TheRouter Debug Mode

    dev

    TheRouter handles its own initialization automatically via FlowTaskExecutor. You do not need to call an init method. However, you can enable or disable debug logging by calling TheRouter.setDebug(boolean) within attachBaseContext of your Application or Activity.

    @Override
    protected void attachBaseContext(Context base) {
        TheRouter.setDebug(true or false);
        super.attachBaseContext(base);
    }
  9. Manage route parameters with addParams() and getExtras()

    dev

    You can attach runtime parameters to a RouteItem using addParams(key, value). These parameters are stored in an internal extras Bundle.

    When calling getExtras(), the RouteItem merges static parameters (defined in the RouteMap.json file) with the runtime extras.

    Priority Rule: Runtime parameters added via addParams() or addAll() have the highest priority and will not be overwritten by static parameters from the routing table.