首页 > 其他分享 >Android使用Dagger注入的方式初始化对象的简单使用

Android使用Dagger注入的方式初始化对象的简单使用

时间:2023-07-18 15:25:16浏览次数:59  
标签:初始化 Dagger Inject fun dagger Android class

一. Dagger简介

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

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

Android官方dagger介绍:https://developer.android.google.cn/training/dependency-injection/dagger-basics?hl=zh-cn

二. Dagger的依赖

// kapt is for implement annotation
apply plugin: 'kotlin-kapt'

// implementation some depend 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 }

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

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

@Module
interface BindRecordModule {
  @ContributesAndroidInjector
  fun bindMainActivity(): MainActivity

  @ContributesAndroidInjector
  fun bindHomeFragment(): HomeFragment
}

3. 定义Component配置moudle

将1和2中的配置配置到Dagger中以生效

@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<Android>

  override fun activityInjector(): AndroidInjector<Android> {
    return activityDispatchingAndroidInjector
  }

  @Inject
  internal lateinit var fragmentDispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>

  override fun supportFragmentInjector(): AndroidInjector<Fragment> {
    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<Fragment>

  override fun supportFragmentInjector(): AndroidInjector<Fragment> {
    return fragmentDispatchingAndroidInjector
  } }

2. Fragment中使用

 AndroidInjection.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
    AndroidInjection.inject(this)
  } }

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

end

标签:初始化,Dagger,Inject,fun,dagger,Android,class
From: https://www.cnblogs.com/bluejump/p/17556989.html

相关文章

  • Android之adb安装busybox使用wget、telnet等服务
    二、通过busybox安装使用wgetbusyboxwget1也可以直接输入wget,不用加busybox了三、通过busybox使用telnet服务(1)进入root权限su1(2)每次开启adbshell后都需要设置环境变量才能重启busybox服务(没有安装busybox可以看DHCPv6之GitHub项目Android侧验证)exportPATH=/data/busybox:......
  • 109.C++类内初始化
    109.C++类内初始化C++11规定,可以为数据成员提供一个类内初始值。创建对象时,类内初始值用于初始化数据成员。像下面这样,cursor和height的类内初始值均为0。classScreen{private: intcursor=0; intheight=0;};1.不能用圆括号给类内初始值的原因C++primer(第5版)中......
  • Android平台如何高效率实现GB28181对接?
    技术背景GB28181协议是一种用于设备状态信息报送的协议,可以在不同设备之间进行通信和数据传输。在安卓系统上实现GB/T28181非常必要,GB28181协议实现分两部分,一部分是信令,另外一部分就是媒体数据的编码。信令主要包括SIPRegister,SIPMessage,SIPInvite,SIPNOTIFY,SIPSUBSCRIBE等......
  • adb如何做Android ui自动化(这一篇就够了)
    一.简介我们都知道在做Androidui自动化的时候用的是appium,环境搭建贼难受。如果我们在工作中遇到需要实现简单的自动化功能,可以直接使用adb来完成,无需去搭建繁琐的appium。ADB(AndroidDebugBridge)是一个用于在Android设备和计算机之间传输数据、安装应用程序、调试和测试Androi......
  • Android 网络游戏开发入门简单示例
    在Android系统上开发是Android开发学习者所向往的,有成就感也有乐趣,还能取得经济上的报酬。那怎样开发Android网络游戏攻略呢?下面介绍一个简单的入门实例。一、创建新工程首先,我们在Eclipse中新建一个名为Movement的工程,并且选择合适的AndroidSDK,在这里,我们选用的API是比较......
  • 详解C#开发Android应用程序的流程
    Android系统一下子铺天盖地而来,让人目不暇接。兴奋的同时也让部分开发人员犯难了!要知道从熟知的Wince、Mobile开发语言C#跨越到RFID-Android的Java。可不是一朝一夕就能完成的。就好比你的乾坤大挪移已经第七层了,却忽然要你从易筋经从头练起,真是愁煞人也!难道微软的开发环境和谷歌......
  • Android之如何看目录&&如何下载他人的项目
    众所周知,目录可以帮助我们快速查找和定位到咱们所需的内容,引导并提供一个整体的概览。所以,今天,咱们就一起来论一论AndroidStudio中的目录!首先,看看它的一个树干结构图:我想大部分同学的软件应该和我下载的一样是英文版的哈......
  • NumPy(1)-常用的初始化方法
    一、NumPy介绍NumPy是Python中科学计算的基础包,它是一个Python库,提供多维数组对象,各种派生对象(如掩码数组和矩阵),以及用于数组快速操作的各种API,有包括数学、逻辑、形状操作、排序、选择、输入输出、离散傅立叶变换、基本线性代数,基本统计运算和随机模拟等等。功能强大的N维......
  • 用android studio如何反编译
    使用AndroidStudio进行反编译在Android开发中,有时我们需要查看或修改其他应用的源代码,这就需要使用反编译工具来还原APK文件的Java源代码。AndroidStudio是一个功能强大的集成开发环境,它提供了反编译工具,可以帮助我们实现这一目的。问题背景假设我们想要查看某个应用的源代码,......
  • androidflexbox
    如何实现"androidflexbox"的步骤介绍在开发Android应用时,我们经常需要使用到灵活的布局,以适应不同屏幕尺寸和设备方向的变化。AndroidFlexbox是一个强大的库,它提供了一种方便的方式来创建灵活的布局,使元素能够自动适应空间,并自动换行。在本文中,我将向你介绍如何使用AndroidFlex......