ray-note/Android Hilt.md

55 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

暂时不写博客,看[官方教程](https://developer.android.google.cn/training/dependency-injection/hilt-android?hl=zh-cn#generated-components))
不纠结于底层细节就看看在学了Android官方的教程之后的总结
### 引入依赖
- 项目根级 `build.gradle.kts`
```
plugins {
// hilt
id("com.google.dagger.hilt.android") version "2.48.1" apply false
}
```
- app 级 `build.gradle.kts`
```
plugins {
...
kotlin("kapt")
id("com.google.dagger.hilt.android")
}
android {
...
}
dependencies {
...
// hilt
implementation("com.google.dagger:hilt-android:2.48.1")
kapt("com.google.dagger:hilt-android-compiler:2.48.1")
}
kapt {
correctErrorTypes = true
}
```
### 为当前的App启用Hilt (必须)
创建一个 Application 的继承类,在 `AndroidManifest.xml` 中的 `application` 中设置当前的Application为这个 `Application` 添加 `@HiltAndroidApp`
### Android Hilt 使用时的容器及层次结构
Hilt 的顶层容器是 `Application` 容器, 这些容器,存在层级关系
- 层级关系如下
- `SingletonComponent::class` -- `Hilt` 根容器, 就是 Application 容器
- `ActivityComponent::class` -- ``
- `FragmentComponent::class`
- `ViewComponent::class`
- `ServiceComponent::class`
- `BroadcastReceiver::class`
-
上面的层级关系中,`SingletonComponent` 是最高层次,依次类推
### Android Hilt 中的作用
- 标注Hilt容器的注解
- `@HiltAndroidApp`
- `@AndroidEntryPoint`
-