본문 바로가기

Android

[Android] API 키 숨기기 (Giraffe 버전과 그 이전 버전) + Manifest사용

Android Studio Giraffe 버전

- local.properties(SDK Location)

## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file should *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
sdk.dir=/Users/usr/Library/Android/sdk
api키="api키" <- API 키를 String타입으로 넣어준다

 

- build.gradle.kts (Module :app)

// buildConfig 사용
import com.android.build.gradle.internal.cxx.configure.gradleLocalProperties

plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
}

android {
    namespace = "com.example.app"
    compileSdk = 34

    defaultConfig {
        applicationId = "com.example.app"

        minSdk = 24
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"

        // buildConfig 사용
        buildConfigField("String", "api키", getKey("api키"))
    }

    buildTypes {
        release {
            isMinifyEnabled = 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"
    }
    buildFeatures {
        viewBinding = true // view binding 추가.
        dataBinding = true // data binding 추가.
        buildConfig = true // buildConfig 사용
    }

}

dependencies {

    implementation("androidx.activity:activity-ktx:1.9.0")
    implementation("androidx.fragment:fragment-ktx:1.7.1")
    implementation("androidx.core:core-ktx:1.13.1")
    implementation("androidx.appcompat:appcompat:1.6.1")
    implementation("androidx.constraintlayout:constraintlayout:2.1.4")
    testImplementation("junit:junit:4.13.2")
    androidTestImplementation("androidx.test.ext:junit:1.1.5")
    androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
}

// buildConfig 사용
fun getKey(propertyKey: String): String {
    return gradleLocalProperties(rootDir).getProperty(propertyKey)
}

 

 

사용시 BuildConfig에 접근하여 api키 변수를 호출할 수 있다.

init {
	val web_client_id = BuildConfig.api키 <- 사용 예제
	val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
		.requestIdToken(web_client_id) 
		.requestEmail()
		.build()
	googleSignInClient = GoogleSignIn.getClient(activity, gso)

}

BuildConfig 할 때에 import는 "com.본인 패키지이름.앱이름.BuildConfig"로 해야하는데,

만약 빨간 밑줄이나 에러가 생긴다면 'File' -> 'invalidate Caches...'를 눌러서 다시 import를 시도해보길 바란다.

 


이전 버전

 

- local.properties(SDK Location)

## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file should *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
sdk.dir=/Users/usr/Library/Android/sdk
api키="api키" <- API 키를 String타입으로 넣어준다

 

 

 

- build.gradle (:app)

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

// Giraffee 이하 버전에서는 밑에 보이는 코드를 추가해줘야한다.
Properties properties = new Properties() 
properties.load(project.rootProject.file('gradle.properties').newDataInputStream())


android {
    namespace 'com.example.app'
    compileSdk 33

    defaultConfig {
        applicationId "com.example.app"
        minSdk 24
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

        renderscriptTargetApi 31
        renderscriptSupportModeEnabled true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

	// Giraffe 이하 버전에서는 buildTypes, productFlavors을 통해 BuildConfigField를 선언해준다.
    buildTypes.each {
        it.buildConfigField "String", "api키", properties['api키']
    }
    productFlavors.each {
        it.buildConfigField "String", "api키", properties['api키']
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        dataBinding true // data binding 추가.
        viewBinding true // view binding 추가.
    }
    sourceSets {
        main {
            renderscript {
                srcDirs 'src/main/rs'
            }
        }
    }
}

 

 

사용 예제는 최신버전과 동일하다

 


AndroidManifest.xml 에서  API Key 사용

근데 Manifest에서 <meta-data> 태그에 api 키를 호출하여 사용해야할 경우가 있다. 

예를 들어 'Google Map SDK' 같은 경우말이다.

 

- AndroidManifest.xml

<meta-data
	android:name="com.google.android.geo.API_KEY"
    	android:value="${googleMapApiKey}" />

 

-build.gradle.kts(앱이름)

plugins {
    id("com.android.application") version "8.1.4" apply false
    id("org.jetbrains.kotlin.android") version "1.8.10" apply false
}

// 나는 아래부분 코드가 없어서, 입력하여 추가해줬다
buildscript {
    dependencies {
        classpath("com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1")
    }
}

 

-build.gradle.kts (:app)

plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
    id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin") // 이부분 추가
}

 

- local.properties

googleMapApiKey="구글 맵 sdk api key"