Hide variables in Android application

This article does not prevent your data in Android application from receiving by decompiling the .apk file.
For further information please read this article.

When you create a open source Android application on GitHub, you probably do not want all your password and API key to be uploaded publicly. One of the ways is to modify the variables every time you publish a build or testing but this is very annoying to do.

Today, I am going to teach you how to use Gradle to achieve that by having a local setting file. First, create a settings.properties text file at the root folder of the Android application.

settings.properties
secretKey1="123"
secretKey2="abc"

Then, open your build.gradle of the module. Add the following lines.

build.gradle
apply plugin: 'com.android.application'

def readSetting() {
    def propsFile = rootProject.file('settings.properties');
    def props = new Properties();
    props.load(new FileInputStream(propsFile));
    return props;
}

android {
    ...
    defaultConfig {
        ...
    }
    buildTypes {
        debug {
            def setting = readSetting();
            buildConfigField "String", "secretKey1", setting["secretKey1"]
            resValue "string", "secretKey2", setting["secretKey2"]
        }
        release {
            def setting = readSetting();
            buildConfigField "String", "secretKey1", setting["secretKey1"]
            resValue "string", "secretKey2", setting["secretKey2"]
            ...
        }
    }
}

dependencies {
    ...
}

You may notice that there are buildConfigField and resValue. buildConfigField will be compile as a Java variable; resValue will be compile as resource. After you modify build.gradle, you need to sync it. After the sync, both of the variables can be used like normal variables.

String secretKey1 = buildConfig.secretKey1;
String secretKey2 = getString(R.string.secretKey2);

Finally, do not forget to add settings.properties to .gitignore.

.gitignore
settings.properties

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s