SoFunction
Updated on 2025-03-01

Detailed analysis of the usage method of ARouter of Android componentization tool

Preface

Components,It is a simple encapsulation of data and methods,Single function,High-class gathering,It is the minimum granularity of business division。 Components化是基于可重用的目的,Use large software systems to separate the focus,拆分成多个独立Components,使得整个软件是单个或多个Components元件组装起来。 How do components communicate? This is due to ARouter.

Android's native routing scheme is the explicit and implicit jump of Intent. It explicitly requires reference to the target, which will lead to coupling of different pages. It is implicitly centrally configured in manifest, which is not conducive to maintenance and management. Moreover, in component development, when each module cannot be directly referenced, the ARouter routing framework comes in handy.

A framework for helping Android Apps to transform components - supports routing, communication, and decoupling between modules

Brief description of the principle

ARouter uses APT technology to generate classes that save the mapping relationship between the path (routing path) and the annotated component class. These classes that save the mapping relationship, postcard to find the target address to be redirected according to the user's request, and use Intent to redirect. Therefore, the core of this framework is to use the mapping relationship generated by APT. The function of APT is to scan and process the annotations in the code during the compilation stage, and then output the Java file according to the annotations.

Basic use

Add dependencies and configuration, note that every module that uses ARouter must be introduced

plugins {
    id ''
    id ''
    id 'kotlin-kapt'
}

    kapt {
        arguments {
            arg("AROUTER_MODULE_NAME", ())
        }
    }

    implementation ':arouter-api:1.5.2'
    kapt ':arouter-compiler:1.5.2'

One thing to note after introduction is: add the following to the file, otherwise it will not be compiled. This is also a small pit I encountered.

=true

Initialize in Application

        if (isDebug()) {
            () //Print log            () //Open debug mode, need to be turned off online        }
        (this)

Add the following annotation on the page that supports routing, the path needs at least two levels

@Route(path = "/home/HomeActivity")
class HomeActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        (savedInstanceState)
        setContentView(.activity_home)
    }
}

Then in another activity, jump

().build("/home/HomeActivity").navigation()

If you need to pass parameters, you can do this

            ().build("/home/HomeActivity")
                .withString("name", "Uncle Xing")
                .withInt("age", 25)
                .withSerializable("user", User("Uncle Xing", 25))
                .navigation()

Then receive it through Autowired in the target activity, ARouter will automatically assign the field without actively obtaining it

@Route(path = "/home/HomeActivity")
class HomeActivity : AppCompatActivity() {
    @JvmField
    @Autowired
    var name = ""
    @JvmField
    @Autowired
    var age = 0
    @JvmField
    @Autowired
    var user: User? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        (savedInstanceState)
        setContentView(.activity_home)
        initView()
    }
    private fun initView() {
        ().inject(this)
        findViewById<TextView>().text = name
        findViewById<TextView>().text = ()
        findViewById<TextView>().text = ()
    }
}

In component development, we usually have some public modules as common functions. At this time, we can use ARouter's dependency injection decoupling and communication of component parts. First, we need to declare the interface, and other components use this interface to call methods

interface MyProvider : IProvider {
    fun getData(): String
}

Implementation Class

@Route(path = "/common/MyProviderImpl")
class MyProviderImpl : MyProvider {
    override fun getData(): String {
        return "Welcome to my blog"
    }
    override fun init(context: Context?) {
    }
}

The activities of other components can be called in this way

class MainActivity : AppCompatActivity() {
    /**
      * When an interface has only one implementation class, Autowired can not set name
      */
    @JvmField
    @Autowired(name = "/common/MyProviderImpl")
    var myProvider: MyProvider? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        (savedInstanceState)
        setContentView(.activity_main)
        initView()
    }
    private fun initView() {
        ().inject(this)
        findViewById&lt;TextView&gt;(.provider_text).text = myProvider?.getData()
    }
}

The above is a method of using dependency injection. You can use it by annotating the fields without actively getting it. In addition, we can also use the method of reliance search. For example, we can also write the above code like this.

class MainActivity : AppCompatActivity() {
    var myProvider: MyProvider? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        (savedInstanceState)
        setContentView(.activity_main)
        initView()
    }
    private fun initView() {
// ().inject(this) This method does not require this sentence        myProvider =
            ().build("/common/MyProviderImpl").navigation() as MyProvider
        /**
          * The methods of discovery include byName and byType. If there is only one implementation of one interface, you can also use byType, which can be written as
          * myProvider = ().navigation(MyProvider::)
          */
        findViewById&lt;TextView&gt;(.provider_text).text = myProvider?.getData()
    }
}

We can also register routes dynamically so that the target page and service can be annotated without @Route. However, generally componentized projects will not do this, and are suitable for projects or other scenarios with some plug-in architectures.

        ().addRouteGroup {
            it["/home/HomeActivity"] = (
                ,       //Route information                HomeActivity::, //Target class                "/home/HomeActivity", //path
                "home",              //Group, try to keep it the same as the first paragraph of path                0, 0
            )
        }

Note: Only routing information registration for the same group is allowed in the same batch.

This is the end of this article about the detailed analysis of the usage method of the Android componentization tool ARouter. For more related Android ARouter content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!