💪 A framework for assisting in the renovation of Android componentization (帮助 Android App 进行组件化改造的路由框架)
💪 A framework for assisting in the renovation of Android componentization (帮助 Android App 进行组件化改造的路由框架)
A framework for assisting in the renovation of Android app componentization
The current development line uses AndroidX natively. Applications consuming it must enable
android.useAndroidX=true; ARouter itself does not require Jetifier. Projects that still use
the legacy Support Library should remain on an ARouter 1.x release until the application has
migrated to AndroidX. The namespace change is a source and binary compatibility boundary, so
its release will be handled as a major-version change.
ARouter's runtime keeps minSdkVersion=14. The demo application and its Gson-based
module-java use minSdkVersion=21; Gson is not an ARouter runtime dependency.
…
Add annotations
// 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 {
...
}
Static route paths must be unique within one module. Route.priority is copied into route
metadata; it is not an override rule and does not select between destinations that declare
the same path.
Initialize the SDK
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
Initiate the routing
// 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();
Add confusing rules (If Proguard is turn on)
…
Using the custom gradle plugin to autoload the routing table
apply plugin: 'com.alibaba.arouter'
buildscript {
repositories {
mavenCentral()
}
dependencies {
// Replace with the latest version
classpath "com.alibaba:arouter-register:?"
}
}
Optional, use the registration plugin provided by the ARouter to automatically load the routing table(power by AutoRegister). By default, the ARouter will scanned the dex files . Performing an auto-registration via the gradle plugin can shorten the initialization time , it should be noted that the plugin must be used with api above 1.3.0!
With Android Gradle Plugin 7.4 or newer, the registration plugin uses the public Scoped Artifacts API and supports Gradle Configuration Cache. Older AGP versions use the legacy Transform API and cannot provide reliable Configuration Cache reuse.
use ide plugin for quick navigation to target class (Optional)
Search for ARouter Helper in the Android Studio plugin market, or directly download the arouter-idea-plugin zip installation package listed in the Latest version above the documentation, after installation
plugin without any settings, U can find an icon at the beginning of the jump code. () click the icon to jump to the target class that identifies the path in the code.
The current plugin recognizes Java and Kotlin ARouter.getInstance().build(...) calls whose paths are string literals or compile-time constants, and it can navigate to @Route destinations.
Jump via URL
// Create a new Activity for monitoring Scheme events, and then directly pass url to ARouter
public class SchemeFilterActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Uri uri = getIntent().getData();
ARouter.getInstance().build(uri).navigation();
finish();
}
}
AndroidManifest.xml
<activity android:name=".activity.SchemeFilterActivity">
<intent-filter>
<data
android:host="m.aliyun.com"
android:scheme="arouter"/>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
</intent-filter>
</activity>
Parse the parameters in the URL
…
…
An interceptor must complete each request exactly once. When redirecting to a login route,
terminate the original request and normally bypass the same interceptor chain for the redirect:
``` java
callback.onInterrupt(new IllegalStateException("Login is required"));
ARouter.getInstance()
.build("/account/login")
.greenChannel()
.navigation(postcard.getContext());
```
Omitting both callback methods leaves the original navigation pending until its timeout.
Processing jump results
// U can get the result of a single jump
ARouter.getInstance().build("/test/1").navigation(this, new NavigationCallback() {
@Override
public void onFound(Postcard postcard) {
...
}
@Override
public void onLost(Postcard postcard) {
...
}
});
// Check the current route table without launching the destination.
// The route group is loaded lazily; invalid or unavailable paths return false.
boolean available = ARouter.getInstance().hasRoute("/test/1");
Custom global demotion strategy
// Implement the DegradeService interface
@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) {
}
}
Decoupled by dependency injection : Service management -- Exposure services
// Declaration interface, other components get the service instance through the interface
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) {
}
}
Decoupled by dependency injection : Service management -- Discovery service
…
Pretreatment Service
@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) {
}
}
Dynamic register route meta Applicable to apps with plug-in architectures or some scenarios where routing information needs to be dynamically registered,Dynamic registration can be achieved through the interface provided by ARouter, The target page and service need not be marked with @Route annotation,Only the routing information of the same group can be registered in the same batch
…
Other settings in initialization
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
API description
…
Get the original URI
String uriStr = getIntent().getStringExtra(ARouter.RAW_URI);
Rewrite URL
// 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;
}
}
Generate router doc
Java modules using annotationProcessor:
// 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"]
}
}
}
}
Kotlin modules must pass the same option through KAPT instead of
javaCompileOptions. The generated file is under build/generated/source/kapt/<variant>/.
The processor remov