The original article is published on wechat public account: Jzman-blog. Welcome to follow and communicate!

The first two articles introduced the basics of Android componentization and the Application process, respectively. Before reading this article, you can read the following two articles:

  • Fundamentals of Android componentization
  • Application for Android componentization

In the process of Android componentization, the interface jump between different modules is also important for the branch factory. If you want to carry out componentization transformation of the project handled by yourself, ARouter is a very easy to get started with routing framework, which is maintained by the development team of Dacang. I believe the quality is no problem.

ARouter is an open-source framework for componentization of An Android App developed by AlBABA team. It supports routing, communication and interception between modules, and is more suitable for componentization development than native jump. This paper summarizes common functions of ARouter through examples, as follows:

  1. ARouter configuration
  2. In-application jump
  3. Parameter hops are carried in the application
  4. The Activity returns the result for processing
  5. Jump and parameter resolution by Uri
  6. Jump between modules
  7. The service call
  8. According to the effect

ARouter configuration

In the corresponding build.gradle file, configure the dependencies for ARouter as follows:

android {
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [AROUTER_MODULE_NAME: project.getName()]
            }
        }
    }
}

dependencies {
    // The API is compatible with the compiler. Use the latest version to ensure compatibility
    compile 'com. Alibaba: arouter - API: 1.4.0'
    annotationProcessor 'com. Alibaba: arouter - compiler: 1.2.1'. }Copy the code

You can choose to configure the automatic routing table loading in the build.gradle file under the project as follows:

// The routing table automatically loads the plug-in
apply plugin: 'com.alibaba.arouter'

buildscript {
    
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com. Android. Tools. Build: gradle: 3.0.1'
        //ARouter
        classpath "Com. Alibaba: arouter - register: 1.0.2"}}Copy the code

In addition, we need to initialize ARouter in Application as follows:

@Override
public void onCreate(a) {
    super.onCreate();
    // Must be configured before initializing ARouter
    if (BuildConfig.DEBUG){
        // Enable log
        ARouter.openLog();
        // The debug mode is enabled. If the install run mode is used, the debug mode must be enabled
        ARouter.openDebug();
    }
    ARouter.init(this);
}
Copy the code

In-application jump

Using ARouter to do an in-app jump is as simple as annotating @route on the Activity you want to jump to.

// The configured path must be at least two levels, such as /xx/ XXX
@Route(path = FirstActivity.PATH)
public class FirstActivity extends AppCompatActivity {

    public static final String PATH = "/test/firstActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); setContentView(R.layout.activity_first); }}Copy the code

Then use the jump method provided by ARouter to jump between applications, as follows:

// In-app redirect
ARouter.getInstance()
        .build(FirstActivity.PATH)
        .navigation();
Copy the code

Parameter hops are carried in the application

ARouter uses a series of methods starting with withString to set the parameters corresponding to it, as follows:

// The application carries parameter hops
ARouter.getInstance()
        .build(SecondActivity.PATH)
        .withString(SecondActivity.PARAM, "This is the parameter that the jump carries.")
        .navigation();
Copy the code

We then use the Intent to get the parameters passed to the Activity we jump to, as follows:

@Route(path = SecondActivity.PATH)
public class SecondActivity extends AppCompatActivity {

    public static final String PATH = "/test/secondActivity";
    public static final String PARAM = "param";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        Intent intent = getIntent();
        if(intent! =null){
            String param = intent.getStringExtra(PARAM);
            Toast.makeText(this, param, Toast.LENGTH_SHORT).show(); }}}Copy the code

The Activity returns the result for processing

The Activity returns results handled in much the same way as the native Activity, that is, with the requestCode when jumping, as follows:

// The Activity returns the result for processing
ARouter.getInstance()
        .build(ThreeActivity.PATH)
        .navigation(this.100);
Copy the code

Then, when the Activity returns, use the Intent parameter setResult, as follows:

@Route(path = ThreeActivity.PATH)
public class ThreeActivity extends AppCompatActivity {

    public static final String PATH = "/test/threeActivity";
    public static final String PARAM_RESULT = "param_result";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_three);
        Intent intent = getIntent();
        //setResult
        intent.putExtra(PARAM_RESULT,"This is the argument that the return carries."); setResult(RESULT_OK,intent); }}Copy the code

Jump and parameter resolution by Uri

ARouter also supports jumping through URIs. First, create an unbounded Activity to listen for Scheme events. The Activity forwards URIs uniformly, and all URIs must pass through this Activity. To improve the security of using Uri jumps somewhat, implement an interface-less Activiry as follows:

public class SchemeFilterActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Uri uri = getIntent().getData();
        // Unify the Uri of external hops to achieve unified distribution of routers, reducing the security risk caused by relying only on Intent attribute matching
        ARouter.getInstance().build(uri).navigation(this.new NavCallback() {
            @Override
            public void onArrival(Postcard postcard) { finish(); }}); }}Copy the code

Host, scheme, and Action are configured in the AndroidManifest file as follows:

<activity android:name=".SchemeFilterActivity">
    <intent-filter>
        <data
            android:host="test.manu.com"
            android:scheme="arouter" />

        <action android:name="com.manu.route" />
        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.BROWSABLE" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>
Copy the code

Next, create an HTML file in the Assets folder and jump the Uri by clicking the jump link. The HTML will look like this:

<! DOCTYPEhtml>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        <h2>Jump test</h2>
        <h2>The custom Scheme</h2>
        <p>
            <! -- without parameters -->
            <a href="arouter://test.manu.com/test/fiveActivity">arouter://test111.manu.com/test/fiveActivity</a>
        </p>
        <p>
            <! -- Take parameters -->
            <a href="arouter://test.manu.com/test/sixActivity?name=alex&age=18&score=%7B%22score%22:%2290%22,%22rank%22:%222%22%7D">arouter://test111.manu.com/test/sixActivity?name=alex&age=18&score={"score":"90","rank":"2"}</a>
        </p>
    </body>
</html>
Copy the code

View the specific effect of the operation diagram.

Then, using the WebView to load the Html, you can jump to the corresponding activities, fiveActivity and SixActivity, which are linked as follows:

// FiveActivity
@Route(path = FiveActivity.PATH)
public class FiveActivity extends AppCompatActivity {

    public static final String PATH = "/test/fiveActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); setContentView(R.layout.activity_five); }}// SixActivity
@Route(path = SixActivity.PATH)
public class SixActivity extends AppCompatActivity {
    public static final String PATH = "/test/sixActivity";
    @Autowired
    public String name;
    @Autowired
    public int age;
    @Autowired
    // If you want to pass a custom object in a Uri, use a JSON string (encodeURI transcode) as an argument, and create a class that implements the SerializationService interface to parse the JSON
    public ScoreBean score;
    @BindView(R.id.tvData)
    TextView tvData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_six);
        ButterKnife.bind(this);
        // Parameter automatic dependency injection
        ARouter.getInstance().inject(this);
        String info = "name=" + name + ",age=" + age + ",score=" + score;
        tvData.setText(info);
        Log.i("SixActivity", info); }}Copy the code

Jump between modules

The jump between the main module and sub-module and sub-module is also very easy. For example, the main module jumps the rotor module. Of course, the main module and sub-module can jump only when ARouter is configured. You can create an interface in the main Module to manage the path of the submodule to jump to, as follows:

// Manage the jump path
public interface Module {
    String MODULE_ONE = "/module1/module-one";
    String MODULE_TWO = "/module2/module-two";
}
Copy the code

Then, jump directly, as follows:

/ / jump Module - one
ARouter.getInstance()
        .build(Module.MODULE_ONE)
        .navigation();
Copy the code

The service call

The Service call in ARouter cannot be confused with the Service in Android. The Service call in ARouter is actually the encapsulation of a certain business. The unified encapsulation of ARouter makes the invocation more convenient, as long as you know the path and name, you can call at will. Implement the IProvider to create a Service as follows:

@Route(path = "/service/singleService")
public class SingleService implements IProvider {
    public static final String PATH = "/service/singleService";
    private Context mContext;

    // Specific services
    public void showMessage(a) {
        Toast.makeText(mContext, "This is a service provided externally.", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void init(Context context) {
        this.mContext = context;
        Log.i("SingleService"."SingleService has init"); }}Copy the code

Then you can call it as follows:

// Call through the service class
ARouter.getInstance().navigation(SingleService.class).showMessage();
// Call through the service class Path
((SingleService) ARouter.getInstance()
        .build(SingleService.PATH)
        .navigation())
        .showMessage();
Copy the code

In addition, you can use dependency injection to complete service invocation, which facilitates management of multiple services. Create a service management class as follows:

// Service management
public class ServiceManage {
    @Autowired
    SingleService singleService;

    public ServiceManage(a){
        // Obtain services through dependency injection
        ARouter.getInstance().inject(this);
    }

    public void getService(a){ singleService.showMessage(); }}Copy the code

The specific service is then invoked through the service management class as follows:

// Service management. Obtain services through dependency injection
ServiceManage manage = new ServiceManage();
manage.getService();
Copy the code

According to the effect

The test effect of the above implementation is shown in the figure below:

ARouter features are comprehensive and easy to use, and the above are the most commonly used. Other features such as interceptors, degrade policies, transitions, mapping groups, and so on can be applied directly to the official documentation.

The source code can be obtained in the public number reply keyword [ARouter].