简体   繁体   中英

Disabling code for release build in Android Gradle

I have const in code that contains some important information:

const val IMPORTANT_CONST = "KEY INFORMATION"

I'm using this const only for debug mode and only temporary (after some time I'll remove it). For now, I'm using build config flag to know if I need to use this const.

How can I hide this const or replace value to an empty string for my release build variant?

You could add it as a BuildConfig field:

In your app gradle script:

buildTypes {
    release {
        buildConfigField("String", "IMPORTANT_CONST ", "\"\"")
    }
    debug {
        buildConfigField("String", "IMPORTANT_CONST ", "\"my secret stuff\"")
    }
}

And in your code:

Log.i("MyApp", "IMPORTANT_CONST = " + BuildConfig.IMPORTANT_CONST );

You can configure the constant in gradle like this:

        android {
    buildTypes {
        debug {
            buildConfigField "String", "IMPORTANT_CONST", "\"KEY INFORMATION\""
        }

        release {
            buildConfigField "String", "IMPORTANT_CONST", "\"\""
        }
    }
}

You can access this variable using BuildConfig.IMPORTANT_CONST

Use BuildConfig which will provide build variant based on your gradle properties.

if (BuildConfig.DEBUG) {
       //Set your constant 
    } else {
         //replace constant value   
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM