ARouter

repository·develop·Indexed 12 days ago

https://github.com/alibaba/arouter

A framework for Android application componentization providing routing and dependency injection. It features route registration via @Route, parameter injection with @Autowired, interceptors for jump logic via IInterceptor, and service discovery using IProvider. The system includes an optional arouter-register plugin for automatic routing table loading and an IntelliJ IDEA plugin for visual navigation via gutter icons.

Tokens
4K
Snippets
15
Records
16
Agent score
91%

What's inside ARouter

  1. How Service Discovery and Dependency Injection work

    develop

    ARouter supports decoupled API calls via Service Discovery.

    1. Expose a Service: Define an interface that extends IProvider and implement it in a class annotated with @Route.
    2. Discover a Service: Use @Autowired on a field to inject the service by type, or use ARouter.getInstance().navigation(ServiceClass.class) to find it by class.

    Note: If multiple implementations of the same interface exist, you must use @Autowired(name = "/path/to/service") to specify which one to inject (by name).

    // 1. Define and Implement Service
    public interface HelloService extends IProvider {
        String sayHello(String name);
    }
    
    @Route(path = "/yourservicegroupname/hello")
    public class HelloServiceImpl implements HelloService {
        @Override
        public String sayHello(String name) { return "hello, " + name; }
        @Override
        public void init(Context context) {}
    }
    
    // 2. Discover Service
    public class Test {
        @Autowired
        HelloService helloService; // Injected by type
    
        @Autowired(name = "/yourservicegroupname/hello")
        HelloService helloService2; // Injected by name
    
        public void test() {
            ARouter.getInstance().inject(this);
            helloService.sayHello("Vergil");
        }
    }
  2. Use Dependency Injection for Service Discovery

    develop

    ARouter supports decoupled component communication via Service management.

    1. Expose a Service: Create an interface that extends IProvider and implement it in a class annotated with @Route.
    2. Discover a Service: Use @Autowired on a field in your consumer class, or use ARouter.getInstance().navigation(ServiceClass.class) to look up the service by type.
    // 1. Define and implement the service
    public interface HelloService extends IProvider {
        String sayHello(String name);
    }
    
    @Route(path = "/yourservicegroupname/hello", name = "test service")
    public class HelloServiceImpl implements HelloService {
        @Override
        public String sayHello(String name) { return "hello, " + name; }
        @Override
        public void init(Context context) {}
    }
    
    // 2. Discover the service
    public class Test {
        @Autowired
        HelloService helloService;
    
        public void testService() {
            ARouter.getInstance().inject(this);
            helloService.sayHello("Vergil");
        }
    }
  3. Install ARouter in Android projects

    develop

    To use ARouter, add the arouter-api and arouter-compiler dependencies to your Gradle configuration. You must also provide the module name to the annotation processor via javaCompileOptions.

    Note: Ensure the versions of arouter-api and arouter-compiler match to maintain compatibility.

    android {
        defaultConfig {
            ...
            javaCompileOptions {
                annotationProcessorOptions {
                    arguments = [AROUTER_MODULE_NAME: project.getName()]
                }
            }
        }
    }
    
    dependencies {
        compile 'com.alibaba:arouter-api:x.x.x'
        annotationProcessor 'com.alibaba:arouter-compiler:x.x.x'
    }
  4. Configure ARouter for Kotlin projects

    develop

    For Kotlin projects, use the kotlin-kapt plugin and configure the kapt block to pass the AROUTER_MODULE_NAME argument.

    apply plugin: 'kotlin-kapt'
    
    kapt {
        arguments {
            arg("AROUTER_MODULE_NAME", project.getName())
        }
    }
    
    dependencies {
        compile 'com.alibaba:arouter-api:x.x.x'
        kapt 'com.alibaba:arouter-compiler:x.x.x'
    }
  5. Install and configure ARouter

    develop

    To use ARouter in an Android project, you must add the arouter-api and arouter-compiler dependencies and configure the AROUTER_MODULE_NAME argument in your annotation processor settings. This argument is required for the compiler to correctly identify the module.

    For standard Gradle projects:

    1. Set AROUTER_MODULE_NAME in javaCompileOptions.
    2. Add arouter-api as a compile dependency.
    3. Add arouter-compiler as an annotationProcessor dependency.
    android {
        defaultConfig {
            ...
            javaCompileOptions {
                annotationProcessorOptions {
                    arguments = [AROUTER_MODULE_NAME: project.getName()]
                }
            }
        }
    }
    
    dependencies {
        // Replace with the latest version
        compile 'com.alibaba:arouter-api:?'
        annotationProcessor 'com.alibaba:arouter-compiler:?'
    }
  6. Enable automatic routing table loading

    develop

    By default, ARrouter scans dex files. To shorten initialization time, you can use the arouter-register plugin to automatically load the routing table. This requires using an API version above 1.3.0.

    apply plugin: 'com.alibaba.arouter'
    
    buildscript {
        repositories {
            mavenCentral()
        }
    
        dependencies {
            classpath "com.alibaba:arouter-register:?"
        }
    }
  7. Initialize the ARouter SDK

    develop

    Initialize ARouter as early as possible, typically in your Application class. If you want to use logging or debugging modes, you must call ARouter.openLog() and ARouter.openDebug() before calling ARouter.init(mApplication).

    Warning: Always disable openDebug() in production versions to avoid security risks.

    if (isDebug()) {
        ARouter.openLog();     // Print log
        ARouter.openDebug();   // Turn on debugging mode
    }
    ARouter.init(mApplication); // As early as possible
  8. Navigate to ARouter routes via IDE gutter icons

    develop

    The ARouter IntelliJ IDEA plugin provides visual navigation markers (gutter icons) in the IDE editor. When you call ARouter.build("/your/path"), a navigation icon appears in the gutter next to the code.

    Clicking this icon allows you to jump directly to the class or method annotated with @com.alibaba.android.arouter.facade.annotation.Route(path = "/your/path") that matches the provided path.

    Supported Usage:

    • Currently, the plugin specifically supports the build(path) method call pattern.
    • If the plugin cannot find a matching route destination, it will trigger an IDE notification with the message: "No destination found or unsupported type."
    // The plugin detects this pattern:
    ARouter.build("/example/path")
    
    // And navigates to the corresponding annotation:
    @Route(path = "/example/path")
    class ExampleActivity : Activity() { ... }
  9. Troubleshooting: No route match error

    develop

    If you see W/ARouter::: ARouter::There is no route match the path [/xxx/xxx], check the following:

    1. Annotation: Ensure the target page has @Route(path="/test/test").
    2. Compiler: Ensure the module containing the target page has arouter-compiler as an annotationProcessor (or kapt) dependency.
    3. Build Logs: Check build logs for ARouter::Compiler >>> to see if the route was discovered.
    4. Debug Mode: If in development, ensure ARouter.openDebug() is called so the mapping table is reloaded every time.
  10. Perform simple navigation and pass parameters

    develop

    Use ARouter.getInstance().build(path) to create a request and .navigation() to execute it. You can chain methods to pass various data types.

    // Simple navigation
    ARouter.getInstance().build("/test/activity").navigation();
    
    // Navigation with parameters
    ARouter.getInstance().build("/test/1")
                .withLong("key1", 666L)
                .withString("key3", "888")
                .withObject("key4", new Test("Jack", "Rose"))
                .navigation();
  11. Perform routing and navigation

    develop

    Use ARouter.getInstance().build(path) to create a request and .navigation() to execute it. You can pass various data types using with... methods.

    // 1. Simple jump
    ARouter.getInstance().build("/test/activity").navigation();
    
    // 2. Jump with parameters
    ARouter.getInstance().build("/test/1")
                .withLong("key1", 666L)
                .withString("key3", "888")
                .withObject("key4", new Test("Jack", "Rose"))
                .navigation();
  12. Register a route with @Route

    develop

    To make an Activity or Fragment navigable via ARouter, annotate the class with @Route. The path must contain at least two levels (e.g., /group/name).

    @Route(path = "/test/activity")
    public class YourActivity extends Activity {
        ...
    }