관리 메뉴

나만을 위한 블로그

[Android] 안드로이드 스튜디오 범블비에서 Hilt 적용하는 법 본문

Android

[Android] 안드로이드 스튜디오 범블비에서 Hilt 적용하는 법

참깨빵위에참깨빵 2022. 5. 8. 16:37
728x90
반응형

DI 라이브러리인 Koin, Dagger2 모두 적용해서 API 호출까지 테스트했지만 Hilt만은 자꾸 에러를 뿜으면서 진행되지 않았다.

방법을 찾아보니 꽤 간단했다. 그 전에 집컴퓨터에서 사용하는 안드로이드 스튜디오 버전 캡쳐 이미지와 ArcticFox 이전 버전과의 몇 가지 차이점을 간략하게 적어놓고 간다.

 

  • 프로젝트 수준 gradle에 작성했던 maven { url "https://jitpack.io" } 는 settings.gradle의 dependencyResolutionManagement {} 안에 적어야 한다
  • 매니페스트에서 <activity> 마다 exported="true"를 적어야 한다. 이걸 false로 둔 채 빌드하면 수정하라는 에러가 뜬다
  • 앱 수준 gradle에 apply plugin: 'com.xxx.xxx' 형태로 적던 것은 이제 plugins {} 안에 id 'com.xxx.xxx' 형태로 적어줘야 한다

 

Hilt를 적용하려면 먼저 프로젝트 수준 gradle을 아래처럼 바꾼다.

 

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext {
        compose_version = '1.0.5'
        hilt_version = '2.40.5'
    }

    dependencies {
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.40.5'
        classpath 'com.google.gms:google-services:4.3.10'
    }
}
plugins {
    id 'com.android.application' version '7.1.3' apply false
    id 'com.android.library' version '7.1.3' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.21' apply false
}

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

 

plugins {} 위에 buildScript {}가 있고 이 안에 hilt 관련 플러그인들이 들어가 있는 걸 볼 수 있다.

그리고 앱 수준 gradle에도 Hilt 관련 의존성들을 추가해준다. plugins {} 안에도 kotlin-kapt, hilt 관련 문구들을 넣어야 한다.

 

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.example.hiltpractice"
        minSdk 26
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    // 아래 2줄 추가
    implementation "com.google.dagger:hilt-android:2.38.1"
    kapt "com.google.dagger:hilt-compiler:2.38.1"
}

 

그리고 간단하게 작동 테스트를 위해 Application 파일과 의존성 주입에 사용할 클래스들을 만든다.

 

import android.app.Application
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class BaseApplication: Application() {
    override fun onCreate() {
        super.onCreate()
    }
}
import javax.inject.Inject

class Car @Inject constructor(brand: Brand, engine: Engine) {
    fun information() {
        println("Car 정보 출력")
    }
}

class Engine @Inject constructor()
class Brand @Inject constructor()

 

이제 메인 액티비티에 @AndroidEntryPoint 어노테이션을 추가하고 Car 안의 메서드를 호출한다.

 

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    @Inject
    lateinit var firstCar: Car

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

        firstCar.information()
    }
}

 

이렇게 하고 앱을 실행하면 로그캣에 문자열이 출력되는 걸 볼 수 있다.

로그캣에 뭔가 많이 올라오기 때문에 println()으로 출력되는 것만 확인하려면 로그캣 검색창에 "Car"라고 쳐서 확인한다.

 

 

참고한 사이트)

 

https://www.youtube.com/watch?v=wWLfMIK0J2U 

 

https://blog.devgenius.io/dependency-injection-with-hilt-kotlin-562963c6c779

 

Dependency Injection with Hilt (Kotlin)

For a long time, Dagger was used to do Dependency Injection operations. However, Hilt has recently been included on of Dagger as a Jetpack…

blog.devgenius.io

 

 
반응형
Comments