### ARouter Standard Route Building
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Demonstrates building standard route requests using ARouter. Supports navigation by path, URI, and starting activities with `startActivityForResult`. It also shows how to pass parameters via Bundle, set flags, and navigate to fragments.
```java
// Build a standard route request
ARouter.getInstance().build("/home/main").navigation();
// Build a standard route request, via URI
Uri uri;
ARouter.getInstance().build(uri).navigation();
// Build a standard route request, startActivityForResult
// The first parameter must be Activity and the second parameter is RequestCode
ARouter.getInstance().build("/home/main", "ap").navigation(this, 5);
// Pass Bundle directly
Bundle params = new Bundle();
ARouter.getInstance()
.build("/home/main")
.with(params)
.navigation();
// Set Flag
ARouter.getInstance()
.build("/home/main")
.withFlags();
.navigation();
// For fragment
Fragment fragment = (Fragment) ARouter.getInstance().build("/test/fragment").navigation();
// transfer the object
ARouter.getInstance()
.withObject("key", new TestObj("Jack", "Rose"))
.navigation();
// Think the interface is not enough, you can directly set parameter into Bundle
ARouter.getInstance()
.build("/home/main")
.getExtra();
```
--------------------------------
### ARouter Configuration for Kotlin Projects
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
Details the setup for ARouter in Kotlin projects using the `kotlin-kapt` plugin. It shows how to apply the plugin and configure annotation processor arguments for module name and documentation generation.
```kotlin
// 可以参考 module-kotlin 模块中的写法
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'
...
}
```
--------------------------------
### Handle Navigation Results with Callback
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
This example shows how to handle the results of a navigation call using a `NavigationCallback`. The callback provides methods like `onFound` and `onLost` to react to the navigation process, allowing for custom handling of successful findings or failures.
```java
ARouter.getInstance().build("/test/1").navigation(this, new NavigationCallback() {
@Override
public void onFound(Postcard postcard) {
...
}
@Override
public void onLost(Postcard postcard) {
...
}
});
```
--------------------------------
### ARouter URL Rewriting Implementation
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Provides an example of implementing the `PathReplaceService` interface to rewrite URLs. The `forString` method handles string paths, and the `forUri` method handles URI types, allowing custom logic for path or URI manipulation.
```java
// Implement the PathReplaceService interface
@Route(path = "/xxx/xxx")
public class PathReplaceServiceImpl implements PathReplaceService {
/**
* For normal path.
*
* @param path raw path
*/
String forString(String path) {
// Custom logic
return path;
}
/**
* For uri type.
*
* @param uri raw uri
*/
Uri forUri(Uri uri) {
// Custom logic
return url;
}
}
```
--------------------------------
### Get Raw URI from Intent
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
Retrieves the raw URI string passed through an Intent, which can be useful for processing original navigation requests or debugging.
```java
String uriStr = getIntent().getStringExtra(ARouter.RAW_URI);
```
--------------------------------
### Get Original URI from Intent
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Retrieves the original URI passed to the activity via the intent. This is useful for inspecting the raw URI that triggered the activity, using the constant `ARouter.RAW_URI`.
```java
String uriStr = getIntent().getStringExtra(ARouter.RAW_URI);
```
--------------------------------
### Initialize ARouter SDK (Java)
Source: https://github.com/alibaba/arouter/blob/develop/README.md
This Java snippet illustrates the initialization process for the ARouter SDK. It includes optional steps to enable logging and debug mode in development builds and emphasizes initializing the SDK as early as possible, preferably in the `Application` class.
```java
if (isDebug()) { // These two lines must be written before init, otherwise these configurations will be invalid in the init process
ARouter.openLog(); // Print log
ARouter.openDebug(); // Turn on debugging mode (If you are running in InstantRun mode, you must turn on debug mode! Online version needs to be closed, otherwise there is a security risk)
}
ARouter.init(mApplication); // As early as possible, it is recommended to initialize in the Application
```
--------------------------------
### Discover Services with ARouter Dependency Injection
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Demonstrates how to use ARouter's dependency injection to discover and use services. It shows both field annotation and lookup methods for obtaining service instances.
```java
public class Test {
@Autowired
HelloService helloService;
@Autowired(name = "/yourservicegroupname/hello")
HelloService helloService2;
HelloService helloService3;
HelloService helloService4;
public Test() {
ARouter.getInstance().inject(this);
}
public void testService() {
// 1. Use Dependency Injection to discover services, annotate fields with annotations
helloService.sayHello("Vergil");
helloService2.sayHello("Vergil");
// 2. Discovering services using dependency lookup, the following two methods are byName and byType
helloService3 = ARouter.getInstance().navigation(HelloService.class);
helloService4 = (HelloService) ARouter.getInstance().build("/yourservicegroupname/hello").navigation();
helloService3.sayHello("Vergil");
helloService4.sayHello("Vergil");
}
}
```
--------------------------------
### Initiate Routing with ARouter (Java)
Source: https://github.com/alibaba/arouter/blob/develop/README.md
This Java code shows how to initiate routing using ARouter. It covers simple navigation within the application and navigation with parameters, including passing primitive types and custom objects.
```java
// 1. Simple jump within application (Jump via URL in 'Advanced usage')
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();
```
--------------------------------
### Generate ARouter Route Documentation (Gradle)
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
Configure your `build.gradle` file to enable ARouter's documentation generation feature. This will output a JSON file containing route mappings, useful for understanding and managing your application's navigation structure.
```gradle
// 更新 build.gradle, 添加参数 AROUTER_GENERATE_DOC = enable
// 生成的文档路径 : build/generated/source/apt/(debug or release)/com/alibaba/android/arouter/docs/arouter-map-of-${moduleName}.json
android {
defaultConfig {
...
javaCompileOptions {
annotationProcessorOptions {
arguments = [AROUTER_MODULE_NAME: project.getName(), AROUTER_GENERATE_DOC: "enable"]
}
}
}
}
```
--------------------------------
### Inject and Use Services with ARouter
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
Demonstrates how to inject services using ARouter's dependency injection and lookup mechanisms. It shows both annotation-based injection and manual lookup via navigation.
```java
ARouter.getInstance().inject(this);
// Using dependency injection
helloService.sayHello("Vergil");
helloService2.sayHello("Vergil");
// Using dependency lookup (byType)
helloService3 = ARouter.getInstance().navigation(HelloService.class);
helloService3.sayHello("Vergil");
// Using dependency lookup (byName)
helloService4 = (HelloService) ARouter.getInstance().build("/yourservicegroupname/hello").navigation();
helloService4.sayHello("Vergil");
```
--------------------------------
### ARouter Configuration for Older Gradle Plugins
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
Provides the configuration steps for integrating ARouter with older Gradle versions using the `android-apt` plugin. This includes applying the plugin, setting up repositories, and configuring annotation processor arguments.
```gradle
apply plugin: 'com.neenbedankt.android-apt'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
}
}
Apt {
arguments {
AROUTER_MODULE_NAME project.getName();
}
}
dependencies {
compile 'com.alibaba:arouter-api:x.x.x'
apt 'com.alibaba:arouter-compiler:x.x.x'
...
}
```
--------------------------------
### ARouter Initialization Settings
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Configure ARouter initialization settings for logging and debugging. ARouter.openLog() enables logging, while ARouter.openDebug() should be enabled during development with InstantRun and disabled for production to avoid security risks. ARouter.printStackTrace() prints thread stacks during logging.
```java
ARouter.openLog(); // Open log
ARouter.openDebug(); // When using InstantRun, you need to open this switch and turn it off after going online. Otherwise, there is a security risk.
ARouter.printStackTrace(); // Print thread stack when printing logs
```
--------------------------------
### ARouter Navigation API Usage
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
Demonstrates various ways to build and navigate routes using ARouter. This includes standard navigation, specifying groups, using URIs, handling startActivityForResult, passing bundles and flags, retrieving fragments, object passing, and applying transition animations.
```java
// 构建标准的路由请求
ARouter.getInstance().build("/home/main").navigation();
// 构建标准的路由请求,并指定分组
ARouter.getInstance().build("/home/main", "ap").navigation();
// 构建标准的路由请求,通过Uri直接解析
Uri uri;
ARouter.getInstance().build(uri).navigation();
// 构建标准的路由请求,startActivityForResult
// navigation的第一个参数必须是Activity,第二个参数则是RequestCode
ARouter.getInstance().build("/home/main", "ap").navigation(this, 5);
// 直接传递Bundle
Bundle params = new Bundle();
ARouter.getInstance()
.build("/home/main")
.with(params)
.navigation();
// 指定Flag
ARouter.getInstance()
.build("/home/main")
.withFlags();
.navigation();
// 获取Fragment
Fragment fragment = (Fragment) ARouter.getInstance().build("/test/fragment").navigation();
// 对象传递
ARouter.getInstance()
.withObject("key", new TestObj("Jack", "Rose"))
.navigation();
// 觉得接口不够多,可以直接拿出Bundle赋值
ARouter.getInstance()
.build("/home/main")
.getExtra();
// 转场动画(常规方式)
ARouter.getInstance()
.build("/test/activity2")
.withTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom)
.navigation(this);
// 转场动画(API16+)
ActivityOptionsCompat compat = ActivityOptionsCompat.
makeScaleUpAnimation(v, v.getWidth() / 2, v.getHeight() / 2, 0, 0);
// ps. makeSceneTransitionAnimation 使用共享元素的时候,需要在navigation方法中传入当前Activity
ARouter.getInstance()
.build("/test/activity2")
.withOptionsCompat(compat)
.navigation();
// 使用绿色通道(跳过所有的拦截器)
ARouter.getInstance().build("/home/main").greenChannel().navigation();
// 使用自己的日志工具打印日志
ARouter.setLogger();
// 使用自己提供的线程池
ARouter.setExecutor();
```
--------------------------------
### Initialize ARouter SDK (Java)
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
This Java code shows the essential steps for initializing the ARouter SDK in your Android application. It includes options for enabling logs and debug mode, which should be configured before calling ARouter.init().
```Java
if (isDebug()) { // These two lines must be written before init, otherwise these configurations will be invalid during the init process
ARouter.openLog(); // Print logs
ARouter.openDebug(); // Enable debug mode (must be enabled if running in InstantRun mode! Turn off for release versions due to security risks)
}
ARouter.init(mApplication); // Initialize as early as possible, recommended in Application
```
--------------------------------
### ARouter Initialization Settings
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
Configure ARouter with options to enable logging, debug mode (especially for InstantRun), and stack trace printing for logs. These settings help in debugging and managing application behavior.
```java
ARouter.openLog(); // 开启日志
ARouter.openDebug(); // 使用InstantRun的时候,需要打开该开关,上线之后关闭,否则有安全风险
ARouter.printStackTrace(); // 打印日志的时候打印线程堆栈
```
--------------------------------
### Initiate a Route Operation (Java)
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
This Java snippet demonstrates how to initiate a routing operation using ARouter. It covers simple in-app navigation and navigation with parameters, including passing primitive types and custom objects.
```Java
// 1. Simple in-app navigation (navigation via URL is in 'Advanced Usage')
ARouter.getInstance().build("/test/activity").navigation();
// 2. Navigate with parameters
ARouter.getInstance().build("/test/1")
.withLong("key1", 666L)
.withString("key3", "888")
.withObject("key4", new Test("Jack", "Rose"))
.navigation();
```
--------------------------------
### Implement ARouter Pretreatment Service
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Shows how to implement a pretreatment service in ARouter. This allows custom logic to be executed before navigation, with the option to return false to handle navigation manually.
```java
@Route(path = "/xxx/xxx")
public class PretreatmentServiceImpl implements PretreatmentService {
@Override
public boolean onPretreatment(Context context, Postcard postcard) {
// Do something before the navigation, if you need to handle the navigation yourself, the method returns false
}
@Override
public void init(Context context) {
}
}
```
--------------------------------
### ARouter Generate Router Documentation
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Configures the Gradle build to generate ARouter documentation. By setting `AROUTER_GENERATE_DOC` to 'enable' in `annotationProcessorOptions` and specifying the `AROUTER_MODULE_NAME`, a JSON file containing the router map will be generated in the build output directory.
```gradle
// Edit build.gradle, add option 'AROUTER_GENERATE_DOC = enable'
// Doc file : build/generated/source/apt/(debug or release)/com/alibaba/android/arouter/docs/arouter-map-of-${moduleName}.json
android {
defaultConfig {
...
javaCompileOptions {
annotationProcessorOptions {
arguments = [AROUTER_MODULE_NAME: project.getName(), AROUTER_GENERATE_DOC: "enable"]
}
}
}
}
```
--------------------------------
### Implement ARouter PretreatmentService
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
Shows how to implement the `PretreatmentService` interface to perform actions before a route is navigated. Returning `false` from `onPretreatment` allows custom handling of the navigation.
```java
@Route(path = "/xxx/xxx")
public class PretreatmentServiceImpl implements PretreatmentService {
@Override
public boolean onPretreatment(Context context, Postcard postcard) {
// Pre-route processing, return false to handle navigation manually
return false;
}
@Override
public void init(Context context) {
}
}
```
--------------------------------
### ARouter Gradle Configuration for Kotlin Projects
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Provides the Gradle configuration for ARouter in Kotlin projects, utilizing the `kotlin-kapt` plugin. It shows how to pass arguments to the kapt compiler, including the module name, and lists the necessary ARouter API and compiler dependencies for a Kotlin environment.
```gradle
// You can refer to the wording in the "module-kotlin" module
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'
...
}
```
--------------------------------
### ARouter Gradle Plugin Configuration (Old Version)
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Details the Gradle configuration for older versions of the ARouter plugin, using `com.neenbedankt.android-apt`. It includes setting up the buildscript repositories and dependencies, configuring apt arguments for module name, and declaring ARouter API and compiler dependencies.
```gradle
apply plugin: 'com.neenbedankt.android-apt'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
}
}
apt {
arguments {
AROUTER_MODULE_NAME project.getName();
}
}
dependencies {
compile 'com.alibaba:arouter-api:x.x.x'
apt 'com.alibaba:arouter-compiler:x.x.x'
...
}
```
--------------------------------
### ARouter Transition Animations
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Shows how to implement transition animations for navigation in ARouter. Supports regular transition animations using `withTransition` and API 16+ animations using `withOptionsCompat`, including shared element transitions.
```java
// Transition animation (regular mode)
ARouter.getInstance()
.build("/test/activity2")
.withTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom)
.navigation(this);
// Transition animation (API16+)
ActivityOptionsCompat compat = ActivityOptionsCompat.
makeScaleUpAnimation(v, v.getWidth() / 2, v.getHeight() / 2, 0, 0);
// ps. makeSceneTransitionAnimation, When using shared elements, you need to pass in the current Activity in the navigation method
ARouter.getInstance()
.build("/test/activity2")
.withOptionsCompat(compat)
.navigation();
```
--------------------------------
### Jump via URL with SchemeFilterActivity
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Demonstrates how to create an Activity to monitor Scheme events and navigate using a provided URL with ARouter. Requires configuration in AndroidManifest.xml.
```java
public class SchemeFilterActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Uri uri = getIntent().getData();
ARouter.getInstance().build(uri).navigation();
finish();
}
}
```
```xml
```
--------------------------------
### ARouter Helper IDE Plugin
Source: https://github.com/alibaba/arouter/blob/develop/README.md
This snippet provides information about the ARouter Helper IDE plugin, which aids in quick navigation to target classes within the ARouter framework, improving developer productivity.
```IDE Plugin
Install ARouter Helper plugin from JetBrains Marketplace.
```
--------------------------------
### Discover Service via Dependency Injection
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
This code demonstrates how to discover and use a service exposed through ARouter's dependency injection. The `@Autowired` annotation is used to inject instances of `HelloService`, either by type or by a specific route path.
```java
public class Test {
@Autowired
HelloService helloService;
@Autowired(name = "/yourservicegroupname/hello")
HelloService helloService2;
HelloService helloService3;
HelloService helloService4;
public Test() {
```
--------------------------------
### Expose Service via Interface for Dependency Injection
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
This section explains how to expose a service using an interface, allowing other components to call it through dependency injection. A `HelloService` interface is defined, and `HelloServiceImpl` implements it, annotated with `@Route` to make it discoverable by ARouter.
```java
public interface HelloService extends IProvider {
String sayHello(String name);
}
@Route(path = "/yourservicegroupname/hello", name = "测试服务")
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
return "hello, " + name;
}
@Override
public void init(Context context) {
}
}
```
--------------------------------
### Expose Services via Dependency Injection
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Demonstrates how to expose services for other components to consume using dependency injection. Define an interface extending IProvider and implement it with @Route.
```java
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) {
}
}
```
--------------------------------
### Declare Interceptor for Jump Process
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Illustrates how to create an interceptor to manage the jump process, such as handling login events. Interceptors execute in priority order between navigation steps.
```java
@Interceptor(priority = 8, name = "test interceptor")
public class TestInterceptor implements IInterceptor {
@Override
public void process(Postcard postcard, InterceptorCallback callback) {
...
// No problem! hand over control to the framework
callback.onContinue(postcard);
// Interrupt routing process
// callback.onInterrupt(new RuntimeException("Something exception"));
// The above two types need to call at least one of them, otherwise it will not continue routing
}
@Override
public void init(Context context) {
// Interceptor initialization, this method will be called when sdk is initialized, it will only be called once
}
}
```
--------------------------------
### Interceptor vs. Service in ARouter
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
Compares ARouter interceptors and services, highlighting their different interfaces and initialization/invocation timings. Interceptors are triggered by any route and initialize asynchronously, potentially delaying the first route if not ready. Services initialize only when called.
--------------------------------
### ARouter Grouping Concept and Usage
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
Explains ARouter's grouping mechanism, where routes are organized into groups for efficient initialization. It shows how to manually assign a group using the `@Route` annotation and the importance of specifying the group during navigation if manually assigned.
```java
@Route(path = "/test/1", group = "app")
```
--------------------------------
### ARouter Register Maven Dependency
Source: https://github.com/alibaba/arouter/blob/develop/README.md
This snippet shows how to include the ARouter register library, used for automatic registration of routes, interceptors, and services within the ARouter framework.
```Gradle
implementation 'com.alibaba:arouter-register:VERSION'
```
--------------------------------
### Navigate via URL with SchemeFilterActivity
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
This snippet demonstrates how to use a SchemeFilterActivity to handle URL-based navigation. The activity listens for specific schemes and hosts, then passes the URI to ARouter for building and navigating. The AndroidManifest.xml configuration is crucial for registering the activity to handle the specified data scheme.
```java
public class SchemeFilterActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Uri uri = getIntent().getData();
ARouter.getInstance().build(uri).navigation();
finish();
}
}
```
```xml
```
--------------------------------
### Dynamically Register Routes with ARouter
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
Illustrates how to dynamically register route information with ARouter, which is useful for plugin architectures. This allows registering routes for pages and services without requiring the `@Route` annotation.
```java
ARouter.getInstance().addRouteGroup(new IRouteGroup() {
@Override
public void loadInto(Map atlas) {
atlas.put("/dynamic/activity", // path
RouteMeta.build(
RouteType.ACTIVITY, // Route meta
TestDynamicActivity.class, // Target Class
"/dynamic/activity", // Path
"dynamic", // Group, try to keep it the same as the first segment of the path
0, // Priority, not used for now
0 // Extra, used to mark the page
)
);
}
});
```
--------------------------------
### Add ARouter Dependencies and Configuration (Gradle)
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
This snippet shows how to add the ARouter API and compiler dependencies to your Android project's build.gradle file. It also includes the necessary annotation processor options for module naming.
```Gradle
android {
defaultConfig {
...
javaCompileOptions {
annotationProcessorOptions {
arguments = [AROUTER_MODULE_NAME: project.getName()]
}
}
}
}
dependencies {
// Replace with the latest version, ensuring api and compiler versions match
compile 'com.alibaba:arouter-api:x.x.x'
annotationProcessor 'com.alibaba:arouter-compiler:x.x.x'
...
}
// For older gradle plugins (< 2.2), use the apt plugin. See 'Other #4' for configuration.
// For Kotlin configuration, see 'Other #5'.
```
--------------------------------
### Enable Automatic Route Table Loading with Gradle Plugin (Gradle)
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
This snippet shows how to apply the ARouter Gradle plugin for automatic route table loading. It also includes the necessary buildscript dependency for the plugin.
```Gradle
apply plugin: 'com.alibaba.arouter'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "com.alibaba:arouter-register:?"
}
}
// Optional: Use ARouter's registration plugin for automatic route table loading (powered by AutoRegister).
// By default, it loads by scanning dex files. Automatic registration via the gradle plugin shortens initialization time and resolves issues with app obfuscation that prevent direct access to dex files, leading to initialization failures.
// Note: This plugin requires api version 1.3.0 or higher!
```
--------------------------------
### Configure ARouter Dependencies and Settings (Gradle)
Source: https://github.com/alibaba/arouter/blob/develop/README.md
This snippet shows how to add ARouter dependencies and configure annotation processor options in your Android project's `build.gradle` file. It specifies the API and compiler dependencies and sets the module name for the annotation processor.
```gradle
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:?'
...
}
// Old version of gradle plugin (< 2.2), You can use apt plugin, look at 'Other#1'
// Kotlin configuration reference 'Other#2'
```
--------------------------------
### Use Custom Gradle Plugin for Autoloading (Gradle)
Source: https://github.com/alibaba/arouter/blob/develop/README.md
This Gradle snippet demonstrates how to apply the ARouter custom gradle plugin for automatic routing table loading. It includes configuring the buildscript dependencies to include the plugin, which can shorten initialization time.
```gradle
apply plugin: 'com.alibaba.arouter'
buildscript {
repositories {
mavenCentral()
}
dependencies {
// Replace with the latest version
classpath "com.alibaba:arouter-register:?"
}
}
```
--------------------------------
### ARouter Compiler Maven Dependency
Source: https://github.com/alibaba/arouter/blob/develop/README.md
This snippet shows how to include the ARouter compiler library, which is essential for annotation processing. It generates the necessary route information for ARouter to function correctly.
```Gradle
annotationProcessor 'com.alibaba:arouter-compiler:VERSION'
```
--------------------------------
### Implement Custom Global Degradation Strategy
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
This demonstrates how to implement a custom global degradation strategy by creating a class that implements the `DegradeService` interface and annotating it with `@Route`. The `onLost` method is called when a route is not found, allowing for fallback behavior.
```java
@Route(path = "/xxx/xxx")
public class DegradeServiceImpl implements DegradeService {
@Override
public void onLost(Context context, Postcard postcard) {
// do something.
}
@Override
public void init(Context context) {
}
}
```
--------------------------------
### Process Jump Results with NavigationCallback
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Shows how to obtain the result of a navigation call by providing a NavigationCallback. This callback allows handling events like finding the destination or losing it.
```java
ARouter.getInstance().build("/test/1").navigation(this, new NavigationCallback() {
@Override
public void onFound(Postcard postcard) {
...
}
@Override
public void onLost(Postcard postcard) {
...
}
});
```
--------------------------------
### ARouter Green Channel and Custom Logging/Executor
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Demonstrates using the 'green channel' to skip interceptors for a specific route and configuring custom logger and thread pool executors for ARouter. The green channel is activated with `.greenChannel()`, and custom logger/executor are set using `ARouter.setLogger()` and `ARouter.setExecutor()` respectively.
```java
// Use green channel (skip all interceptors)
ARouter.getInstance().build("/home/main").greenChannel().navigation();
// Use your own log tool to print logs
ARouter.setLogger();
// Use your custom thread pool
ARouter.setExecutor();
```
--------------------------------
### ARouter API Maven Dependency
Source: https://github.com/alibaba/arouter/blob/develop/README.md
This snippet shows how to include the ARouter API library in your Android project using Maven Central. It's a core dependency for using ARouter's navigation and injection features.
```Gradle
implementation 'com.alibaba:arouter-api:VERSION'
```
--------------------------------
### Custom Global Degrade Strategy
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Explains how to implement a custom global degradation strategy by implementing the DegradeService interface. This is used when a route cannot be found.
```java
@Route(path = "/xxx/xxx")
public class DegradeServiceImpl implements DegradeService {
@Override
public void onLost(Context context, Postcard postcard) {
// do something.
}
@Override
public void init(Context context) {
}
}
```
--------------------------------
### ARouter Path Replacement Service
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
Implement the `PathReplaceService` interface to customize or replace routing paths. This allows for dynamic path management based on specific rules or conditions.
```java
// 实现PathReplaceService接口,并加上一个Path内容任意的注解即可
@Route(path = "/xxx/xxx") // 必须标明注解
public class PathReplaceServiceImpl implements PathReplaceService {
/**
* For normal path.
*
* @param path raw path
*/
String forString(String path) {
return path; // 按照一定的规则处理之后返回处理后的结果
}
/**
* For uri type.
*
* @param uri raw uri
*/
Uri forUri(Uri uri) {
return url; // 按照一定的规则处理之后返回处理后的结果
}
}
```
--------------------------------
### Annotate Activities for Routing (Java)
Source: https://github.com/alibaba/arouter/blob/develop/README.md
This Java code demonstrates how to annotate an Android Activity to make it discoverable by ARouter for routing. The `@Route` annotation is used with a path parameter, which must have at least two levels (e.g., `/xx/xx`).
```java
// Add annotations on pages that support routing (required)
// The path here needs to pay attention to need at least two levels : /xx/xx
@Route(path = "/test/activity")
public class YourActivity extend Activity {
...
}
```
--------------------------------
### Annotate Target Activity for Routing (Java)
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
This Java code demonstrates how to annotate an Activity to make it discoverable by ARouter for navigation. The @Route annotation specifies the path for the activity, which must have at least two segments.
```Java
// Add annotation to the routable page (required)
// The path must have at least two segments, e.g., /xx/xx
@Route(path = "/test/activity")
public class YourActivity extends Activity {
...
}
```
--------------------------------
### Dynamically Register Route Meta with ARouter
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Illustrates dynamic route registration using ARouter, suitable for plug-in architectures. This method allows registering routes without the @Route annotation, but only for the same group in a batch.
```java
ARouter.getInstance().addRouteGroup(new IRouteGroup() {
@Override
public void loadInto(Map atlas) {
atlas.put("/dynamic/activity", // path
RouteMeta.build(
RouteType.ACTIVITY, // Route type
TestDynamicActivity.class, // Target class
"/dynamic/activity", // Path
"dynamic", // Group
0, // not need
0 // Extra tag, Used to mark page feature
)
);
}
});
```
--------------------------------
### Proguard Rules for ARouter
Source: https://github.com/alibaba/arouter/blob/develop/README.md
This section provides essential Proguard rules required when Proguard is enabled in your Android project to ensure ARouter functions correctly. It includes rules for keeping routing-related classes and interfaces.
```proguard
-keep public class com.alibaba.android.arouter.routes.**{*;}
-keep public class com.alibaba.android.arouter.facade.**{*;}
-keep class * implements com.alibaba.android.arouter.facade.template.ISyringe{*;}
# If you use the byType method to obtain Service, add the following rules to protect the interface:
-keep interface * implements com.alibaba.android.arouter.facade.template.IProvider
# If single-type injection is used, that is, no interface is defined to implement IProvider, the following rules need to be added to protect the implementation
# -keep class * implements com.alibaba.android.arouter.facade.template.IProvider
```
--------------------------------
### Declare Additional Information for Target Page with extras
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
This snippet shows how to extend the `Route` annotation with the `extras` attribute to pass additional information to the target page. The `extras` attribute is an integer, allowing for up to 32 boolean flags through bitwise operations, which can be used for conditional logic in interceptors.
```java
@Route(path = "/test/activity", extras = Consts.XXXX)
```
--------------------------------
### Add Proguard Rules for ARouter (Proguard)
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
This configuration provides the necessary Proguard rules to ensure ARouter functions correctly after code obfuscation. It includes rules for keeping route-related classes and interfaces.
```Proguard
-keep public class com.alibaba.android.arouter.routes.**{*;}
-keep public class com.alibaba.android.arouter.facade.**{*;}
-keep class * implements com.alibaba.android.arouter.facade.template.ISyringe{*;}
# If using byType to get Services, add the following rule to protect interfaces
-keep interface * implements com.alibaba.android.arouter.facade.template.IProvider
# If using single-class injection, i.e., not defining an interface implementing IProvider, add the following rule to protect implementations
# -keep class * implements com.alibaba.android.arouter.facade.template.IProvider
```
--------------------------------
### Declare Interceptors for Navigation Process
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
This code illustrates how to declare interceptors using the @Interceptor annotation. Interceptors can process navigation requests before they reach the target, useful for tasks like authentication or logging. The `process` method handles the navigation, and `onContinue` or `onInterrupt` must be called.
```java
@Interceptor(priority = 8, name = "测试用拦截器")
public class TestInterceptor implements IInterceptor {
@Override
public void process(Postcard postcard, InterceptorCallback callback) {
...
callback.onContinue(postcard); // 处理完成,交还控制权
// callback.onInterrupt(new RuntimeException("我觉得有点异常")); // 觉得有问题,中断路由流程
// 以上两种至少需要调用其中一种,否则不会继续路由
}
@Override
public void init(Context context) {
// 拦截器的初始化,会在sdk初始化的时候调用该方法,仅会调用一次
}
}
```
--------------------------------
### Parse Parameters with @Autowired
Source: https://github.com/alibaba/arouter/blob/develop/README_CN.md
This section explains how to parse parameters for activities using the @Autowired annotation. It covers basic type mapping, aliasing parameters with `name`, passing custom objects via JSON, and handling collections like Lists and Maps. A custom SerializationService can be implemented for JSON parsing.
```java
@Route(path = "/test/activity")
public class Test1Activity extends Activity {
@Autowired
public String name;
@Autowired
int age;
@Autowired(name = "girl")
boolean boy;
@Autowired
TestObj obj;
@Autowired
List list;
@Autowired
Map> map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ARouter.getInstance().inject(this);
Log.d("param", name + age + boy);
}
}
@Route(path = "/yourservicegroupname/json")
public class JsonServiceImpl implements SerializationService {
@Override
public void init(Context context) {
}
@Override
public T json2Object(String text, Class clazz) {
return JSON.parseObject(text, clazz);
}
@Override
public String object2Json(Object instance) {
return JSON.toJSONString(instance);
}
}
```
--------------------------------
### Parse URL Parameters with @Autowired
Source: https://github.com/alibaba/arouter/blob/develop/README.md
Shows how to declare fields annotated with @Autowired to automatically parse parameters from a URL. Supports basic types and custom objects via JSON serialization.
```java
@Route(path = "/test/activity")
public class Test1Activity extends Activity {
@Autowired
public String name;
@Autowired
int age;
@Autowired(name = "girl") // Map different parameters in the URL by name
boolean boy;
@Autowired
TestObj obj; // Support for parsing custom objects, using json pass in URL
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ARouter.getInstance().inject(this);
// ARouter will automatically set value of fields
Log.d("param", name + age + boy);
}
}
// If you need to pass a custom object, Create a new class(Not the custom object class),implement the SerializationService, And use the @Route annotation annotation, E.g:
@Route(path = "/yourservicegroupname/json")
public class JsonServiceImpl implements SerializationService {
@Override
public void init(Context context) {
}
@Override
public T json2Object(String text, Class clazz) {
return JSON.parseObject(text, clazz);
}
@Override
public String object2Json(Object instance) {
return JSON.toJSONString(instance);
}
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.