본문 바로가기

안드로이드/안드로이드

[안드로이드] Api Key 저장 방법 with local.properties

프로젝트를 하다 보면 Api를 사용하게 되는데 Api에는 Key가 필요하다.

 

그러나 이 Key를 그냥 복붙 후 Git에 올려버리면 누군가 해당 Key를 사용할 수 있고, 최악의 경우 막대한 금전적 손실을 입을 수 있다.

 

Key 같이 중요한 데이터는 숨겨야하는데 Git에는 gitignore가 있고, 여기에는 local.properties가 자동으로 설정되어 있다.

 

따라서, local.properties 에 Key를 저장해 두고 프로젝트에서 갖다 쓰면 된다.

 

사용 방법

local.properties

## 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=C\:\\Users\\KDOY\\AppData\\Local\\Android\\Sdk
api_key="abcde"

 

 

build.gradle (Module)

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())

android{
    ...
    defaultConfig {
    	buildConfigField "String", "API_KEY", properties['api_key']
    }
}

 

1. sync now

2. Build -> Rebuild Project

 

 

프로젝트에서 다음과 같이 사용할 수 있다.

val api_key = BuildConfig.API_KEY  //abcde