Android 模块间通信

参考:https://blog.csdn.net/lianwa88/article/details/79973958

注意事项:

1 ARouter的引用在Java和kotlin中不同

Kotlin (推荐)

1 在basemodule中添加引用
   api 'com.alibaba:arouter-api:1.5.1'
   kapt 'com.alibaba:arouter-compiler:1.5.1'
2 「每个module」中添加下面代码(注意)
apply plugin: 'kotlin-kapt'
javaCompileOptions {
            annotationProcessorOptions {
                arguments = [AROUTER_MODULE_NAME: project.getName()]
            }
        }
  kapt 'com.alibaba:arouter-compiler:1.5.1'

JAVA

1 在basemodule中添加引用
 api 'com.alibaba:arouter-api:1.5.1'
 annotationProcessor 'com.alibaba:arouter-compiler:1.5.1'
2 每个module中添加下面代码(注意)
javaCompileOptions {
            annotationProcessorOptions {
                arguments = [AROUTER_MODULE_NAME: project.getName()]
            }
        }
   annotationProcessor 'com.alibaba:arouter-compiler:1.5.1'

示例代码:

image.png

步骤:

1 base目录下创建IBaseService接口
2 创建IBaseService实现类,BaseService
3 被调用方receiver,定义路由TestService
4 调用方caller,获取service对象,获取数据

base module

1 IBaseService

import com.alibaba.android.arouter.facade.template.IProvider

interface IBaseService<T> : IProvider {
  fun getData(): T?
  fun setData(t: T?)
}

2 BaseService

import android.content.Context

open class BaseService<T> : IBaseService<T> {
    var t: T? = null
    override fun getData(): T? {
        return t
    }

    override fun init(context: Context?) {
    }

    override fun setData(t: T?) {
        this.t = t
    }
}

2 ProviderHelper (获取service工具类)

import com.alibaba.android.arouter.launcher.ARouter

class ProviderHelper {
    companion object {
        fun getService(): BaseService<String?> {
            return ARouter.getInstance().build("/test/receiver").navigation() as BaseService<String?>
        }
    }
}

receiver module

1 TestService

import com.alibaba.android.arouter.facade.annotation.Route
import com.example.base.BaseService

@Route(path = "/test/receiver")
class TestService : BaseService<String?>() {
    override fun getData(): String? {
        setData("sssss")
        return super.getData()
    }
}

caller module调用

 var service = ProviderHelper.getService()
 var msg = service.getData()
 Toast.makeText(this@CallerActivity, msg, Toast.LENGTH_SHORT).show()

项目地址:https://github.com/nxtzhengyongbo/AndroidModule

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容