How to use Android Injector for Activity and Fragment objects through New Dagger 2 (with Kotlin)

2020-11-22 21:24:01

参考地址 参考文章 https://medium.com/@serapbercin001/how-to-use-android-injector-for-activity-and-fragment-objects-through-new-dagger-2-with-kotlin-704eb8a98c43



This article is regarding how to implement dagger 2 with new approach, It brought giant change and in this way getting ride of boilerplate code through dagger 2.x new release. However I don’t compare between old and new dagger structure so I just have developed a simple sample from scratch about that and basically touch on @Component@Module@ContributesAndroidInjectorAndroidInjection.inject(this)AndroidSupportInjection.inject(this).

If you want to use these, first of all we should set up gradle:

Set up gradle:

kapt 'com.google.dagger:dagger-compiler:2.16'
kapt 'com.google.dagger:dagger-android-processor:2.16'
implementation 'com.google.dagger:dagger-android-support:2.16'

i added kapt instead of annotationProcessor for kotlin. we dont need to keep annotationProcessor dependency. Also we have to add kotlin-plugin in gradle.

apply plugin: 'kotlin-kapt'

Basically Package Structure:


Let’s start to create ApplicationComponent interface that is root in our dagger graph. It may includes more modules that just listed here. For instance; api module, shared preference module and something like that. I started to add AndroidInjectionModule as a module in the component. This module should be installed in the component that is used to inject. AndroidInjectionModule also is internal module, it was created by Dagger, it includes binding activity, fragment, service, broadcastReciver and content provider. We will add ActivitiesModule module later on.

@Singleton
@Component(modules = AndroidInjectionModule::class)
interface ApplicationComponent {

  fun inject(application: Application)

  @Component.Builder
  interface Builder {

     fun build(): ApplicationComponent

     @BindsInstance
     fun applicationBind(application: Application): Builder

  }
}

Let’s start to write ActivitiesModule as a subcomponent, we will use @ContributesAndroidInjector annotation type. After that we will add it in ApplicationComponent as a module.

@Module
abstract class ActivitiesModule {
  @ContributesAndroidInjector(modules =    [(MainActivityModule::class)])
  abstract fun contributeActivityAndroidInjector(): MainActivity

}

@ContributesAndroidInjector can takes modules, Modules to be installed in the generated. I’ll explain the MainActiviyModule that what should include, also with @Bind annotation . By the way If module needs scope, we can create spesific Scope, for instance; @ActivityScope, @FragmentScope..

import javax.inject.Scope

@Scope
@MustBeDocumented
annotation class ActivityScope

if you need it, we can add scope like here.

@ActivityScope
@ContributesAndroidInjector(modules = [(ActivityModule::class)])
abstract fun contributeActivityAndroidInjector(): MainActivity

Dagger 2 includes HasActivityInjector as a new that provides AndroidInjector and should implement in Application class, also we should inject DispatchingAndroidInjector that’s mean return activityInjector, in this way we’ll use AndroidInjection.inject() for activity and fragment.

class SampleApplication : Application(), HasActivityInjector {

   @Inject
   lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity>


   override fun onCreate() {
       super.onCreate()
       DaggerApplicationComponent.builder()
               .applicationBind(this)
               .build()
               .inject(this)

   }

   override fun activityInjector(): AndroidInjector<Activity> = dispatchingAndroidInjector

}

We can use AndroidInjection.inject(this) in activity after inject DispatchingAndroidInjector in application.

AndroidInjection.inject(this) should calls in onCreate method before super. That’s all!!

class MainActivity : AppCompatActivity(){ override fun onCreate(savedInstanceState: Bundle?) {
  AndroidInjection.inject(this)
  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_main)
}
}

you can see generated file below that code was created by dagger after rebuild. Remember, via androidInjector.inject(this) we passed activity, it gets DispatchingAndroidInjector<Activity> from application.

private DispatchingAndroidInjector<Activity> getDispatchingAndroidInjectorOfActivity() {
 return DispatchingAndroidInjector_Factory.newDispatchingAndroidInjector(
     getMapOfClassOfAndProviderOfFactoryOf());
}

DispatchingAndroidInjector looks up AndroidInjector.Factory, it is below the code snippet. it creates your activities subcomponent builder, and pass the activities to inject your activities.

private Map<Class<? extends Activity>, Provider<AndroidInjector.Factory<? extends Activity>>>
   getMapOfClassOfAndProviderOfFactoryOf() {
 return MapBuilder
     .<Class<? extends Activity>, Provider<AndroidInjector.Factory<? extends Activity>>>
         newMapBuilder(2)
     .put(MainActivity.class, (Provider) mainActivitySubcomponentBuilderProvider)
     .put(SecondActivity.class, (Provider) secondActivitySubcomponentBuilderProvider)
     .build();
}

Inject Fragment Object

So far, We injected Activity object.Well, How we can inject fragment object. We will modify activity class to inject fragment object and implement HasSupportFragmentInjector or HasFragmentInjector interface. HasSupportFragmentInjector is for android.support.v4.app.Fragment and HasFragmentInjector is for android.app.Fragment after that we pass fragment in DispatchingAndroidInjector, that’s looks here.

class MainActivity : AppCompatActivity(), HasSupportFragmentInjector {

  @Inject
  lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>

  override fun onCreate(savedInstanceState: Bundle?) {
     AndroidInjection.inject(this)
     super.onCreate(savedInstanceState)
     setContentView(R.layout.activity_main)
  }

  override fun supportFragmentInjector() = dispatchingAndroidInjector

}

Also, we create Fragment module same way with the activity.

@Module
abstract class FragmentModule {

  @ContributesAndroidInjector
  abstract fun contributeMainFragment(): MainFragment
}

If you need to add MainFragmentModule, simply add like this;

@ContributesAndroidInjector(modules = [(MainFragmentModule::class)])

we should specify FragmentModule in our root graph after created fragment module

@Component(modules = [AndroidSupportInjectionModule::class,
  ActivitiesModule::class,
  FragmentModule::class])

now we can inject fragment object. For fragment we can call AndroidSupportInjection.inject(this) in onAttach method before super.

class MainFragment : Fragment() {

  override fun onAttach(context: Context?) {
     AndroidSupportInjection.inject(this)
     super.onAttach(context)

  }

  override
  fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                   savedInstanceState: Bundle?): View? {
     return inflater.inflate(R.layout.main_fragment, container, false)
  }

}

That’s all:) You also can find source code GitHub.


  • 2019-08-13 20:06:42

    修改 Nginx 进程最大可打开文件数(worker_processes和worker_connections)

    worker_processes:操作系统启动多少个工作进程运行Nginx。注意是工作进程,不是有多少个nginx工程。在Nginx运行的时候,会启动两种进程,一种是主进程master process;一种是工作进程worker process。例如我在配置文件中将worker_processes设置为4,启动Nginx后,使用进程查看命令观察名字叫做nginx的进程信息,我会看到如下结果:

  • 2019-08-14 09:01:18

    linux下高并发服务器实现

    在做网络服务的时候tcp并发服务端程序的编写必不可少。tcp并发通常有几种固定的设计模式套路,他们各有优点,也各有应用之处。下面就简单的讨论下这几种模式的差异:

  • 2019-08-14 13:18:59

    Linux系统下CPU使用(load average)梳理

    在平时的运维工作中,当一台服务器的性能出现问题时,通常会去看当前的CPU使用情况,尤其是看下CPU的负载情况(load average)。对一般的系统来说,根据cpu数量去判断。比如有2颗cup的机器。如果平均负载始终在1.2以下,那么基本不会出现cpu不够用的情况。也就是Load平均要小于Cpu的数量。

  • 2019-08-14 14:27:35

    计算密集型和IO密集型

    在进行I/O操作的时候,是将任务交给DMA来处理,请求发出后CPU就不管了,在DMA处理完后通过中断通知CPU处理完成了。I/O操作消耗的cpu时间很少.

  • 2019-08-14 14:29:12

    浅谈nodejs和php

    现在,Web开发公司和开发人员可以选择多种技术栈来构建Web应用程序。早期网络发展,不同的技术被用于前端和后端开发。但是,随着Node.js的发布,布局发生了变化,因为它允许开发人员使用 JavaScript 编写后端代码。这最终催生了MEAN(MongoDB + Express +AngularJS + NodeJS )堆栈 web 开发框架,从前端到后端甚至是数据库(MongoDB -JSON)都使用 JavaScript。在 Node.js 之前,Web 开发通常是在 PHP 的帮助下完成的,因为它很容易与 HTML 集成,帮助开发人员立即构建动态网站。在这篇文章中,我们将比较 Node.js 和 PHP,看哪一个最适合当前的行业需求。

  • 2019-08-15 13:32:18

    Node.js是如何解决服务器高性能瓶颈问题的

    在Java、PHP或者.net等服务器端语言中,会为每一个客户端连接创建一个新的线程。而每个线程需要耗费大约2MB内存。也就是说,理论上,一个8GB内存的服务器可以同时连接的最大用户数为4000个左右。要让Web应用程序支持更多的用户,就需要增加服务器的数量,而Web应用程序的硬件成本当然就上升了。

  • 2019-08-15 13:33:53

    nodejs的10个性能优化技巧

    在我接触JavaScript(无论浏览器还是NodeJS)的时间里,总是遇到有朋友有多线程的需求。而在NodeJS方面,有朋友甚至直接说到,NodeJS是单线程的,无法很好的利用多核CPU。那么我们在使用过程中,就要非常注意性能优化了

  • 2019-08-16 13:18:48

    使用ffmpeg进行ts切片并AES-128加密

    由于解密的key文件都是公开的,所以并不能算上完全加密,用户只要把你的key+m3u8里的ts切片文件全部下载,用ffmpeg还是能解,这时就要考虑url的key防止用户直接下载和盗链。 ​

  • 2019-08-18 22:22:54

    Error:error: unable to remove file: Permission denied

    JNI里写的C++增加了函数或修改了,如果此时是Debug模式下,而且还没退出程序,就出现这个Permission denied的提示。解决也很简单:就是退出App即可。如果退出无响应,直接拔usb,重新插上也可以