AndRouter Documentation

repository·master·Indexed 20 days ago

https://github.com/campusappcn/androuter

An Android framework for mapping URLs to Activities or specific actions. It provides a centralized routing mechanism using schemes, hosts, and paths, supporting Activity navigation via annotations or initializer classes, web browser redirection, and custom router implementations. Features include path parameter extraction with type support, routing interceptors for authentication or blacklisting, and integration via Gradle.

Tokens
2.3K
Snippets
7
Records
8
Agent score
22%

What's inside AndRouter

  1. Initialize the ActivityRouter

    master

    The ActivityRouter maps URLs to Android Activities. You can initialize it in your Application class using two different methods:

    1. Using Java Annotations

    Annotate your Activity classes with @RouterMap containing the desired URLs. Then, call Router.initActivityRouter(Context) in your Application's onCreate().

    2. Using an Initializer Class

    Provide an implementation of IActivityRouteTableInitializer to manually map URLs to Activity classes. This is useful for dynamic routing or complex path patterns.

    // Method 1: Annotation
    @RouterMap({"activity://second", "activity://second2"})
    public class SecondActivity extends Activity { ... }
    
    // In Application class
    public class App extends Application {
        @Override
        public void onCreate() {
            super.onCreate();
            Router.initActivityRouter(getApplicationContext());
        }
    }
    
    // Method 2: Initializer class
    Router.initActivityRouter(getApplicationContext(), new IActivityRouteTableInitializer() {
        @Override
        public void initRouterTable(Map<String, Class<? extends Activity>> router) {
            router.put("activity://first/:s{name}/:i{age}/birthday", FirstActivity.class);
        }
    });
  2. Implement a custom Router

    master

    You can extend the routing capabilities by implementing BaseRouter and BaseRoute.

    1. Implement BaseRouter: Define how to open routes, how to retrieve a route object from a URL, and which scheme your router handles via canOpenTheUrl.
    2. Implement BaseRoute: Define the specific logic for the route instance.
    3. Register: Add your router instance to the RouterManager using Router.addRouter(new YourCustomRouter()).
    private static class TestRouter extends BaseRouter {
        @Override
        public void open(IRoute route) { Timber.i(route.getUrl()); }
    
        @Override
        public void open(String url) { Timber.i(url); }
    
        @Override
        public IRoute getRoute(String url) { return new TestRoute(this, url); }
    
        @Override
        public boolean canOpenTheRoute(IRoute route) { return (route instanceof TestRoute); }
    
        @Override
        public boolean canOpenTheUrl(String url) { 
            return TextUtils.equals(UrlUtils.getScheme(url), "test"); 
        }
    
        @Override
        public Class<? extends IRoute> getCanOpenRoute() { return TestRoute.class; }
    }
    
    private static class TestRoute extends BaseRoute {
        public TestRoute(IRouter router, String url) { super(router, url); }
    }
    
    // Register the router
    Router.addRouter(new TestRouter());
  3. Install AndRouter via Gradle

    master

    To use AndRouter, you must configure your project's Gradle files to include the necessary repositories, the android-apt plugin, and the AndRouter dependencies.

    Note: Do not add the jitpack.io repository under the buildscript block.

    // 1. In your project-level build.gradle
    buildscript {
        dependencies {
            classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        }
    }
    
    allprojects {
        repositories {
            jcenter()
            maven { url "https://jitpack.io" }
        }
    }
    
    // 2. In your app-module build.gradle
    apply plugin: 'android-apt'
    
    dependencies {
        compile 'com.github.campusappcn.AndRouter:router:1.2.8'
        apt 'com.github.campusappcn.AndRouter:compiler:1.2.8'
    }
  4. Initialize the BrowserRouter

    master

    The BrowserRouter allows you to open web URLs using the system browser. Initialize it in your Application class's onCreate() method.

    public class App extends Application {
        @Override
        public void onCreate() {
            super.onCreate();
            Router.initBrowserRouter(getApplicationContext());
        }
    }
  5. Use Interceptors to control routing

    master

    Interceptors allow you to intercept a routing request before it is executed. This is useful for implementing blacklists (redirecting to an error page) or authentication checks (redirecting to a login page).

    Implement the Interceptor interface and register it using Router.setInterceptor(Interceptor).

    Router.setInterceptor(new Interceptor() {
        @Override
        public boolean intercept(Context context, String url) {
            if (url.equals("http://www.souhu.com")) {
                Router.open(context, "activity://error");
                return true; // Intercepted
            }
            return false; // Continue routing
        }
    });
  6. Use the Activity Router to open activities

    master

    Once initialized, you can use the Router class to navigate between activities using URLs. AndRouter provides several ways to handle the transition:

    • Basic Open: Router.open(String url)
    • With Animation: Use Router.getRoute(url) to get an ActivityRoute object, then call .setAnimation(context, enterAnim, exitAnim).open().
    • For Result: Use .withOpenMethodStartForResult(context, requestCode).open() to handle onActivityResult.
    • With Extra Parameters: Use .withParams(key, value).open() to add additional data to the Intent that isn't part of the URL path.
    // Basic open
    Router.open("activity://second/汤二狗");
    
    // Open with animation
    ActivityRoute activityRoute = (ActivityRoute) Router.getRoute("activity://second/汤二狗");
    activityRoute.setAnimation(this, R.anim.in_from_left, R.anim.out_to_right).open();
    
    // Open for result
    ((ActivityRoute) Router.getRoute("activity://second/汤二狗"))
        .withOpenMethodStartForResult(this, 200)
        .open();
    
    // Add extra parameters
    ((ActivityRoute) Router.getRoute("activity://third"))
        .withParams("date", new Date())
        .open();
  7. Define Route URL path parameters and types

    master

    AndRouter uses a specific syntax for path segments to extract values and pass them as Intent extras. A path segment is defined using a colon : followed by a type prefix and a key name.

    Warning: If a URL matches a route but the value type does not match the definition, a RuntimeException will be thrown.

    Key FormatTypeDescription
    :i{key}integerInteger value
    :f{key}floatFloat value
    :l{key}longLong value
    :d{key}doubleDouble value
    :s{key} or :{key}stringString value
    :c{key}charCharacter value

    Example: A route activity://first/:s{name}/:i{age} matched with activity://first/kris/26 will result in intent.getStringExtra("name") returning "kris" and intent.getIntExtra("age", 0) returning 26.