Gradle Hilt 配置速查

APP gradle 文件

关注 plugin + dependencies

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'

android {
    compileSdkVersion rootProject.compileSdkVersion
    buildToolsVersion rootProject.buildToolsVersion
    defaultConfig {
        applicationId "com.xiangxue.arch_demo"
        minSdkVersion rootProject.minSdkVersion
        targetSdkVersion rootProject.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    dataBinding {
        enabled true
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation "com.google.android.material:material:$rootProject.androidXVersion"
    implementation "androidx.appcompat:appcompat:$rootProject.androidXVersion"
    implementation "androidx.constraintlayout:constraintlayout:$rootProject.constraint_version"
    implementation 'q.rorbin:badgeview:1.1.3'
    implementation project(':news')
    implementation project(':base')

    implementation "com.google.dagger:hilt-android:2.28-alpha"
    kapt "com.google.dagger:hilt-android-compiler:2.28-alpha"


}

Project gradle

关注dependencies classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
/*        maven {
            url 'http://localhost:8083/artifactory/android_group/'
        }*/
        maven {
            url 'https://maven.aliyun.com/repository/google'
        }
        maven {
            url 'https://maven.aliyun.com/repository/jcenter'
        }
        maven {
            url 'https://maven.aliyun.com/repository/public'
        }
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.1'
        
        //hilt here
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'

    }
}

allprojects {
    repositories {
/*        maven {
            url 'http://localhost:8083/artifactory/android_group/'
        }*/
        maven {
            url 'https://maven.aliyun.com/repository/google'
        }
        maven {
            url 'https://maven.aliyun.com/repository/jcenter'
        }
        maven {
            url 'https://maven.aliyun.com/repository/public'
        }
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

ext {
    minSdkVersion = 21
    targetSdkVersion = 28
    androidXVersion = '1.0.0'
    compileSdkVersion = 28
    buildToolsVersion = '28.0.3'
    constraint_version = '1.1.3'

 
}

模块中和jetpack的结合配置 gradle

...
dependencies {
  ...
  implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha01'
  // When using Kotlin.
  kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha01'
  // When using Java.
  annotationProcessor 'androidx.hilt:hilt-compiler:1.0.0-alpha01'
}

gradle 配置 说明 end

------------------------------------------------------------------------------------------------------------------------------

标签配置 说明


标签配置

@HiltAndroidApp 在应用的Application配置,顶级容器

@AndroidEntryPoint 依赖注入

下面的都可以用这个

Activity
Fragment
View
Service
BroadcastReceiver

【规则】

  • @AndroidEntryPoint 为某个 Android 类添加注释,则还必须为依赖于该类的 Android 类添加注释
  • 如果您为某个 Fragment 添加注释,则还必须为使用该 Fragment 的所有 Activity 添加注释。
  • @AndroidEntryPoint 会为项目中的每个 Android 类生成一个单独的 Hilt 组件。这些组件可以从它们各自的父类接收依赖项,如组件层次结构中所述
  • @AndroidEntryPoint - @Inject 一对
@AndroidEntryPoint
public class ExampleActivity extends AppCompatActivity {

  @Inject
  AnalyticsAdapter analytics;
  ...
}

构造函数依赖

public class AnalyticsAdapter {

  private final AnalyticsService service;

  @Inject
  AnalyticsAdapter(AnalyticsService service) {
    this.service = service;
  }
  ...
}
  • @Module 模块
    1 接口不能用inject
    2不属于这个类的依赖,并不能用构造函数进行inject常见外部库
    @Module - @InstallIn 一对
    必须使用 @InstallIn 为 Hilt 模块添加注释,以告知 Hilt 每个模块将用在或安装在哪个 Android 类中

  • @Binds 针对接口,告知接口的实现

Hilt 模块 AnalyticsModule 带有 @InstallIn(ActivityComponent::class) 注释,因为您希望 Hilt 将该依赖项注入 ExampleActivity。此注释意味着,AnalyticsModule 中的所有依赖项都可以在应用的所有 Activity 中使用。

public interface AnalyticsService {
  void analyticsMethods();
}

// Constructor-injected, because Hilt needs to know how to
// provide instances of AnalyticsServiceImpl, too.
public class AnalyticsServiceImpl implements AnalyticsService {
  ...
  @Inject
  AnalyticsServiceImpl(...) {
    ...
  }
}

@Module
@InstallIn(ActivityComponent.class)// 所有Activity中可以
public abstract class AnalyticsModule {

  @Binds
  public abstract AnalyticsService bindAnalyticsService(
    AnalyticsServiceImpl analyticsServiceImpl
  );
}
  • @Provides

1 接口不是无法通过构造函数注入类型的唯一一种情况。如果某个类不归您所有(因为它来自外部库,如 RetrofitOkHttpClientRoom 数据库等类)

2 或者必须使用构建器模式创建实例 也无法通过构造函数注入。

如何做: 您可以告知 Hilt 如何提供此类型的实例,方法是在 Hilt 模块内创建一个函数,并使用 @Provides 为该函数添加注释。

@Module
@InstallIn(ActivityComponent.class)
public class AnalyticsModule {

  @Provides
  public static AnalyticsService provideAnalyticsService(
    // Potential dependencies of this type
  ) {
      return new Retrofit.Builder()
               .baseUrl("https://example.com")
               .build()
               .create(AnalyticsService.class);
  }
}

复杂用法 为同一类型提供多个绑定 例如 OKHttp 多个拦截器,参考官网 OKHttp 多个拦截器

  • @ApplicationContext 和 @ActivityContext 限定符 限定符
public class AnalyticsAdapter {

  private final Context context;
  private final AnalyticsService service;

  @Inject
  AnalyticsAdapter(
    @ActivityContext Context context,
    AnalyticsService service
  ) {
    this.context = context;
    this.service = service;
  }
}


Hilt 组件 声明周期和对应关系

Hilt 组件 注入器面向的对象
ApplicationComponent Application
ActivityRetainedComponent ViewModel
ActivityComponent Activity
FragmentComponent Fragment
ViewComponent View
ViewWithFragmentComponent 带有 @WithFragmentBindings 注释的 View
ServiceComponent Service

生命周期

生成的组件 创建时机 销毁时机
ApplicationComponent Application#onCreate() Application#onDestroy()
ActivityRetainedComponent Activity#onCreate() Activity#onDestroy()
ActivityComponent Activity#onCreate() Activity#onDestroy()
FragmentComponent Fragment#onAttach() Fragment#onDestroy()
ViewComponent View#super() 视图销毁时
ViewWithFragmentComponent View#super() 视图销毁时
ServiceComponent Service#onCreate() Service#onDestroy()
  • @ViewModelInject ---@Assisted jetpack viewmodel

你可能感兴趣的:(Gradle Hilt 配置速查)