头图
This article has been published on the WeChat public account "Code Xiaosheng" for the first time. You can search and follow and focus on Android technology sharing.

Necessary instructions

This article is only a case demonstration to facilitate learning and mastering of basic knowledge, and does not conduct source-level exploration. Let's first clarify the functions that can be achieved, the technical points used and the environment.

Technical points:

  • Multi-module project, including baseLib, main APP, and multi-service modules
  • Multiple modules, realize that a module can run independently
  • Jump between multiple modules, use ARouter framework
  • ARouter interceptor use

environment:

  • Android Studio4.1.2
  • Language: Java
  • Mobile phone: Samsung A6s Android10

Routing application scenario

Android's project structure development is more and more inclined to multiple modules, and if the jump between modules uses the native method ( Intent jump), then as the project develops and grows, it will eventually lead to the intricate import xxx , which will bring maintenance A lot of trouble, as shown below:

不使用路由的多模块

black line: indicates the dependency. With the dependency, you can refer to the classes of other modules in the current module, and you can use Intent jump. <br/>
Blue line: It means that you want to jump to a certain page of the login, live, and work modules from the app module, and you must rely on the corresponding module to refer to the related class to realize the jump. <br/>
red line: For business needs, you can directly enter the live room from the work module, then the work module must rely on the live module; vice versa. <br/>
Green line: When the user is not logged in, or the login status is invalid, or the account is logged in elsewhere, then you need to jump from the current module to the login module, so other basic modules must rely on the login module.

In this way, with the expansion of project functions, the problems brought about are obvious.

The ARouter solves this problem very well. The official website address: https://github.com/alibaba/ARouter/ , its function is very powerful, for multi-module projects, whether it is componentized or not, it solves the maintenance caused by interdependence and jumps. cost. The following simple diagram:

使用路由的多模块

black line: indicates the dependency relationship. The dependency here is mainly to solve the problem of resource sharing, not to jump. If you don't use the resources in baselib, you don't need to rely on it. <br/>
Other dashed lines: indicate that page jumps and communication can be realized without mutual dependence. This is the power of routing. <br/>

Engineering Module configuration

New Construction

I named it MyArouter here, and then respectively new Module: baseLib , circle , home select Android Library type, the compilation is completed as shown in the figure below, it is normal;

Add dependency

The win system uses the shortcut key Ctrl+Shift+Alt+S call up the Project Structure panel. Of course, you can also open this panel File->Project Structure

Project Structure

As shown in the figure, select different modules and add dependent modules. My dependency here is like this:

  • App module dependency: baseLib , circle , home
  • baseLib module: does not rely on any functional modules
  • baseLib module dependency: 06170e5d2902ce
  • Home module dependency: baseLib

module description

  • baseLib : The public basic modules of the project, which can generally include shared tools, public resources, public code snippets, shared tripartite references, etc., can be placed here, which can avoid a lot of duplication of code, improve the readability of the code and the program Easy to maintain.
  • app : It is the host module of the entire project, which means that the priority of this module is higher than other functional modules, because the main entrance of the program is here.
  • Other modules are divided according to business functions and are responsible for specific businesses.

Project ARouter configuration

The first step: baseLib module configuration

Open baseLib under build.gradle file, dependencies add the following code at

api 'com.alibaba:arouter-api:1.5.2'

Then create a new baseLib BaseApplication , the complete code is as follows:

public class BaseApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        initRouter(this);
    }

    public static void initRouter(Application application) {
        if (BuildConfig.DEBUG) {
            ARouter.openLog();
            ARouter.openDebug();
        }
        ARouter.init(application);
    }

}

Then create a new class ARouterPath , the function of this class is to provide a unified route to the page path, that is, the path value in ARouter;

public class ARouterPath {

    public static final String CIRCLE_CIRCLE="/circle/home";

}

Step 2: Other module configuration

app , circle , home modules, open the corresponding build.gradle file

  • Add the following code under dependencies

    annotationProcessor 'com.alibaba:arouter-compiler:1.5.2'
  • Add the following code under defaultConfig

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

At this point, in fact, the routing reference configuration has been completed, but we have not added the Application, and it is very simple. Under the app module, create a new AppApplication inherited from BaseApplication and add it to the manifest file under the module.

public class AppApplication extends BaseApplication {

}
The implementation is not done here because it demonstrates the demo and does not use third-party things, and it can be initialized according to the needs in actual development. The reason for inheritance is that we have initialized the routing configuration earlier.

Test ARouter jump

We have finished the configuration work. The main purpose of this article is to test the page jump. Of course, the jump will include whether it carries parameters, whether the jump needs to have a return value, and whether it can jump between modules without dependencies. The following groupings test:

findViewById() : In order to avoid writing 06170e5d29079c, I used ViewBinding here. The usage is very simple, you can understand it at a glance, and I won’t explain it in detail here.

Use routing jumps within the module

In the module, you can use intent to jump, but the subject of this article is to explore the jump usage of routing. Here I take the jump in the app module as an example, and create a new MyInfoActivity , which displays the default values. MainActivity carries parameter jump assignment to show usage examples.

跳转传参

If your configuration is correct and you still cannot jump, then uninstall the APP and run it again, it is Ok, because the routing address path is mapped and cached. Although it is changed later, the cache is still used.

Reference Description

ARouter provides a variety of ways to pass parameters, and also supports native parameter value types, as shown below:

ARouter传参方法

The use of all methods is not demonstrated here, as long as the following commonly used ones are understood, the others are similar.

  • with(Bundle bundle) : If you want to pass multiple parameters, it is recommended to use this method.
  • withBundle(String key, Bundle bundle) : Still pass a Bundle, but you can customize the key.
  • with package data type (String key, basic data type value): If only one parameter is passed, and it is a basic data type, then these methods are very practical.

Other commonly used things like passing serialized objects, collections, etc., please try yourselves. Let's talk about how to take parameters. The following code is the parameter MyInfoActivity

ARouter.getInstance().build(ARouterPath.APP_MY_INFO)
          .withInt(KEY_TYPE, 100)
          .withString(KEY_NAME, "codexiaosheng")
          .withString(KEY_WEIXIN, "xiaoshengcode")
          .navigation();

supplement : Some careful friends may have noticed, how to write a jump with return value?

navigation

  • The third method is equivalent to our original writing startActivityForResult()
  • The fourth method also provides monitoring, which will be used for the interception function to be shared later.

take reference

Corresponding to the above three parameter passing methods:

  • with(Bundle bundle) : Take the parameters and getIntent().getExtras() , and then it is the same as our original usage.
  • withBundle(String key, Bundle bundle) and with package data type (String key, basic data type value): The method of taking parameters is the same, you can first look at the code MyInfoActivity
@Route(path = ARouterPath.APP_MY_INFO)
public class MyInfoActivity extends AppCompatActivity {

    private ActivityMyInfoBinding myInfoBinding;

    @Autowired
    public int u_type;
    @Autowired(name = MainActivity.KEY_NAME)
    public String uName;
    @Autowired(name = MainActivity.KEY_WEIXIN)
    public String uWeixin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myInfoBinding = ActivityMyInfoBinding.inflate(getLayoutInflater());
        setContentView(myInfoBinding.getRoot());

        ARouter.getInstance().inject(this);

        myInfoBinding.tvName.setText("name:" + uName + " 用户类型:" + u_type);
        myInfoBinding.tvWeixin.setText("weixin:" + uWeixin);
    }

}

It can be seen that there are several differences between this and the parameters we usually take:

  1. The @Autowired annotation is used
  2. ARouter.getInstance().inject(this); this line of code
  3. The fields that receive the parameters are all public modifiers
  4. There is no explicit getXXX value code

Description of @Autowired annotations:<br/>

  • The annotated variable must be public
  • If the name of the variable is not the same as the key of the passed parameter, you need to manually add the name to the annotation, that is, the key of the passed parameter.

Except with(Bundle bundle) this way of passing parameters, other methods need to add the following line of code on the page that receives the parameters:

ARouter.getInstance().inject(this);

If you use the with(Bundle bundle) parameter transfer method, then take the parameters to getIntent().getExtras() , and just operate.

In general, it looks relatively simple, with a lot of judgment code missing.

Jump between modules

Here I use with(Bundle bundle) to pass parameters for demonstration. First look at an overall effect:

效果

This way of passing parameters, neither added to the received page @Autowired notes, they do not add ARouter.getInstance().inject(this); this line of code, use our original way getIntent().getExtras() can be.

The above demonstration effect involves the jump from the app home and circle modules, the home module and the circle module to jump to each other. Remember the previous dependencies? home and circle have no dependencies directly, but they can be jumped directly through routing. If our project has more modules, this will be very convenient and reduce code coupling.

Take a look at the code to home

// 跳转home模块页面
mainBinding.jumpHomePage.setOnClickListener(v -> {
    if (mainBinding.cbHome.isChecked()) {
        Bundle bundle = new Bundle();
        bundle.putInt(KEY_TYPE, 500);
        bundle.putString(KEY_NAME, "home module");
        bundle.putString(KEY_WEIXIN, "is home module~");

        ARouter.getInstance().build(ARouterPath.HOME_HOME).with(bundle).navigation();
    } else {
        ARouter.getInstance().build(ARouterPath.HOME_HOME).navigation();
    }
});

The core code is posted, and the basic demonstration function is completed. This article is based on java to demonstrate, kotlin configuration reference official website.

Regarding the advanced use of routing, such as interception and module can be run separately, the next blog will be announced.

Jump principle

ARouter automatically registers through annotations and generates the mapping relationship during compilation. The file can be loaded at runtime, and the target page can be smoothly jumped to through the path.

Summary of this article

  1. Can't see the corresponding R.layout.xxx_layout file name, you can jump to the corresponding xml XXXBinding.getRoot()
  2. If there are many jumps between modules of the project, it is recommended to use routing jumps uniformly
  3. ARouter can also jump to fragment , see the official demo for specific use
  4. Common jump animation settings, ARouter jump is also possible, just input the animation resource file id
Get all the code in this article: follow the WeChat public code Xiaosheng reply arouter

code小生
165 声望18 粉丝