美文网首页
Android 模块间通信

Android 模块间通信

作者: 郑永博 | 来源:发表于2020-11-16 17:45 被阅读0次

    参考: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

    相关文章

      网友评论

          本文标题:Android 模块间通信

          本文链接:https://www.haomeiwen.com/subject/yjezbktx.html