Search code examples
javaandroidkotlinandroid-module

How is data transferred between modules in Android?


How do I transfer data between modules? B module implements A module. So module B can access module A. But module A cannot access to module B. How can I send data from the some activity in module A to the some activity in module B? The activity in module B is always open (I don't kill activity in module B when activity in A module is running) and I cannot use the intent structure, I end the activity in module A with finish(). Activity in module A cannot reach activity in module B already.

There is the following code in the gradle file of module B.

implementation project(':ModuleA')

Solution

  • I solved this problem with the method below.

    In Module B, I start ModuleAActivity.

    startActivityForResult(Intent(this,ModuleAActivity::class.java),1)
    

    InModule A, I set the data.

    var returnIntent = intent
    returnIntent.putExtra("result",myData)
    setResult(1, returnIntent)
    finish()
    

    Then In Module B again, I get the data.

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1) {
            if (resultCode == 1) {
                val result = data?.getSerializableExtra("result")
            }
            if (resultCode == Activity.RESULT_CANCELED) {
    
            }
        }
    }