程序与技术分享:Android使用Dagger注入的方式初始化对象的简单使用

简介: 程序与技术分享:Android使用Dagger注入的方式初始化对象的简单使用

一. Dagger简介


Dagger 2 是 Google 开源的一款依靠注入结构,它的前身是 square 的 Dagger 1,Dagger 2 在 Android 中有着较为广泛的运用。


Dagger 2 根据 Java 注解,采用 annotationProcessor(注解处理器) 在项目编译时动态生成依靠注入需求的 Java 代码,然后咱们在合适的位置手动完结终究的依靠注入,而不是 Dagger 1 中根据反射的解决方案,所以在性能上是有保障的。


Android官方dagger介绍://代码效果参考:http://hnjlyzjd.com/xl/wz_24269.html


二. Dagger的依赖


// kapt is for implement annotation


apply plugin: 'kotlin-kapt'


// implementation dependences for dagger


implementation "com.google.dagger:dagger:2.21"


implementation "com.google.dagger:dagger-android-support:2.21"


kapt "com.google.dagger-compiler:2.21"


kapt "com.google.dagger-android-processor:2.21"


二. Dagger的配置


1. 初始化对象配置


1.1 使用@Inject注解初始化对象


注意:使用@Inject注解初始化对象时,构造函数所需的参数也必须已经使用dagger初始化,否则编译时会报错:com.record.sample.** cannot be provided without an @Inject constructor or an @Provides-annotated method


1 @Singleton


2 class RecordContractImple @Inject constructor(): RecordContract{


3   // empty body


4 }


1 @Singleton


2 class PicruteAdapter @Inject constructor(


3 context: Context


4 ): RecyclerView.Adapter{


5   // empty body


6 }


1.2 使用provide注解初始化对象


@Module


class RecordModule {


  @Provides


  @Singleton


  fun provideRecordAdapter(


    context: Context


  ): RecordAdapter = RecordAdapter(context)


  @Provides


  @Singleton


  fun provideRecordContract(


    recordContractImpl: RecordContractImpl  


  ): RecordContract = recordContractImpl


  @Provides


  @Singleton


  fun provideApplication(application: RecordApplication): RecordApplication = application


  @Provides


  @Singleton


  fun provideContext(application: RecordApplication): Context = application


}


使用@Named注解可以为同一个类初始化不同的对象,在页面中可以使用@Inject+@Named注解类使用该对象,但使用时一直报错: cannot be provided without an @Inject constructor or an @Provides-annotated method,原因未知。


// use @Named annotation to provide different instance for the same class


@Provides


@Singleton


@Named("Okhttp_client")


fun provideOkHttpClient(): OkHttpClient


@Provides


@Singleton


fun provideRetrofit(


  // use the @Named annotation to use different instance for same class


  @Named("Okhttp_client") okHttpClient: OkHttpClient


): Retrofit {


  return RetrofitProvide(...)


}


可以初始化基本类型


@Provider


fun provideAppVersion(): String = "2.21.0"


初始化Set,需要使用@ElementsIntoSet注解,网传dagger2.25以上版本有时候不需要显示提供@ElementsIntoSet注解。


@IntoSet注解告诉Dagger将返回的对象添加到Set依赖项中。


@Singleton


@Provides


@ElementsIntoSet


fun provideSet(): Set {


  val set = mutableSetOf()


  set.add("a")


  set.add("b")


  set.add("c")


  return set


}


@Singleton


@Provides


@ElementsIntoSet


fun provideSet2(): Set {


  val set = mutableSetOf()


  set.add("a")


  set.add("b")


  set.add("c")


  return set


}


@Provides


@IntoSet


fun provideInstanceForSet(): Name {


  return Name()


}


2. 绑定页面与使用Dagger初始化的对象


设置哪些页面可以使用@Inject方式获取Dagger初始化的对象。(ContributesAndroidInjector参数设置待确认)


@Module


interface BindRecordModule {


  @ContributesAndroidInjector


  fun bindMainActivity(): MainActivity


  @ContributesAndroidInjector


  fun bindHomeFragment(): HomeFragment


}


3. 定义Component配置moudle


将1和2中的配置配置到Component中,配置完点击make module后,Dagger会自动生成一个DaggerRecordComponent。


@Singleton


@Component(


  modules = 【


    // default module, must add


    AndroidSupportInjectionModule::class,  


    RecordModule::class,


    BindRecordModule::class,


  】


)


interface RecordComponent {


  @Component.Builder


  interface Builder {


    @BindsInstance


    fun application(application: Application): Builder


    fun build(): RecordComponent


  }


  fun inject(app: RecordApplication)


完成后点击Make Module,Dagger会自动生成类DaggerRecordComponent


4. 重写Application,配置Component


class RecordApplication: Application(), HasActivityInjector, HasSupportFragmentInjector {


  override fun onCreate() {


    DaggerRecordComponent.builder().


      .application(this)


      .build()


      .inject(this)


      super.onCreate()


  }


  @Inject


  internal lateinit var activityDispatchingAndroidInjector: DispatchingAndroidInjector


  override fun activityInjector(): AndroidInjector {


    return activityDispatchingAndroidInjector


  }


  @Inject


  internal lateinit var fragmentDispatchingAndroidInjector: DispatchingAndroidInjector


  override fun supportFragmentInjector(): AndroidInjector {


    return fragmentDispatchingAndroidInjector


  }


}


三. 使用


1. Activity中使用


AndroidInjection.inject(this)可以放在onAttach或者onCreate方法中初始化,只要在使用dagger初始化的地方之前调用即可。


HasSupportFragmentInjector可要可不要,原因未知。


class MainActivity: AppCompatActivity, HasSupportFragmentInjector {


  // use inject anotation to init instance, do not use private, otherwise the param will not init


  @Inject


  lateinit var recordContract: RecordContract


  override fun onCreate(savedInstanceState: Bundle?) {


    super.onCreate(savedInstanceState)


    // pass activity instance to dagger for init the param


    AndroidInjection.inject(this)


    // use the instance function directily


    val name = recordContract.getName()


  }


  @Inject


  internal lateinit var fragmentDispatchingAndroidInjector: DispatchingAndroidInjector


  override fun supportFragmentInjector(): AndroidInjector {


    return fragmentDispatchingAndroidInjector


  }


}


2. Fragment中使用


AndroidSupportInjection.inject(this)可以放在onAttach或者onCreate方法中初始化,只要在使用dagger初始化的地方之前调用即可。


class HomeFragment: Fragment() {


  // use inject anotation to init instance, do not use private, otherwise the param will not init


  @Inject


  lateinit var recordContract: RecordContract    


  override fun onAttach(context: Context) {


    super.onAttach(context)


    // pass activity instance to dagger for init the param


    AndroidSupportInjection.inject(this)


  }


}


不断更新中,技术讨论可以留言,谢谢。


end

相关文章
|
1月前
|
存储 消息中间件 人工智能
【08】AI辅助编程完整的安卓二次商业实战-修改消息聊天框背景色-触发聊天让程序异常终止bug牵涉更多聊天消息发送优化处理-优雅草卓伊凡
【08】AI辅助编程完整的安卓二次商业实战-修改消息聊天框背景色-触发聊天让程序异常终止bug牵涉更多聊天消息发送优化处理-优雅草卓伊凡
131 10
【08】AI辅助编程完整的安卓二次商业实战-修改消息聊天框背景色-触发聊天让程序异常终止bug牵涉更多聊天消息发送优化处理-优雅草卓伊凡
|
1月前
|
存储 消息中间件 人工智能
【05】AI辅助编程完整的安卓二次商业实战-消息页面媒体对象(Media Object)布局实战调整-按钮样式调整实践-优雅草伊凡
【05】AI辅助编程完整的安卓二次商业实战-消息页面媒体对象(Media Object)布局实战调整-按钮样式调整实践-优雅草伊凡
79 11
【05】AI辅助编程完整的安卓二次商业实战-消息页面媒体对象(Media Object)布局实战调整-按钮样式调整实践-优雅草伊凡
|
安全 Android开发 Kotlin
Android经典面试题之Kotlin延迟初始化的by lazy和lateinit有什么区别?
**Kotlin中的`by lazy`和`lateinit`都是延迟初始化技术。`by lazy`用于只读属性,线程安全,首次访问时初始化;`lateinit`用于可变属性,需手动初始化,非线程安全。`by lazy`支持线程安全模式选择,而`lateinit`适用于构造函数后初始化。选择依赖于属性特性和使用场景。**
418 5
Android经典面试题之Kotlin延迟初始化的by lazy和lateinit有什么区别?
|
Oracle Java 关系型数据库
Android studio 安装以及第一个程序
Android studio 安装以及第一个程序
364 0
|
Web App开发 JavaScript 前端开发
Android端使用WebView注入一段js代码实现js调用android
Android端使用WebView注入一段js代码实现js调用android
323 0
|
存储 传感器 定位技术
《移动互联网技术》 第四章 移动应用开发: Android Studio开发环境的使用方法:建立工程,编写源程序,编译链接,安装模拟器,通过模拟器运行和调试程序
《移动互联网技术》 第四章 移动应用开发: Android Studio开发环境的使用方法:建立工程,编写源程序,编译链接,安装模拟器,通过模拟器运行和调试程序
373 0
|
网络协议 Android开发 虚拟化
Android Studio无法运行程序调试程序出现Unable to connect to ADB.Check the Event Log for possible issues.Verify th
Android Studio无法运行程序调试程序出现Unable to connect to ADB.Check the Event Log for possible issues.Verify th
179 0
Android Studio无法运行程序调试程序出现Unable to connect to ADB.Check the Event Log for possible issues.Verify th
|
Android开发
【Android 逆向】代码调试器开发 ( 等待进程状态改变 | detach 脱离进程调试 PTRACE_DETACH | 调试中继续运行程序 PTRACE_CONT )
【Android 逆向】代码调试器开发 ( 等待进程状态改变 | detach 脱离进程调试 PTRACE_DETACH | 调试中继续运行程序 PTRACE_CONT )
276 0
|
前端开发 开发工具 Android开发
使用expo在安卓模拟器中运行React Native程序
看完这篇教程你会学到如何在安卓模拟器里运行一个React Native程序。 我的电脑及软件环境 系统: windows10 64 Node:8.5.0 然后安装下面的工具,不分先后。
3245 0
|
Android开发
【Android 逆向】修改运行中的 Android 进程的内存数据 ( Android 系统中调试器进程内存流程 | 编译内存调试动态库以及调试程序 )
【Android 逆向】修改运行中的 Android 进程的内存数据 ( Android 系统中调试器进程内存流程 | 编译内存调试动态库以及调试程序 )
351 0
【Android 逆向】修改运行中的 Android 进程的内存数据 ( Android 系统中调试器进程内存流程 | 编译内存调试动态库以及调试程序 )

热门文章

最新文章

下一篇
oss教程