Android: Using Build Variant to Separate Debug Settings from Release Codes

CHEN SU
CS Random Thoughts on Tech
3 min readJul 23, 2020

--

Problem Description

  • There are cases that debug codes need to be added for the convenience of development.
  • Sometimes the debug codes could expose sensitive data, which is a security risk if those codes are compiled and shipped with the product. Normal users won’t be able to see it, but hackers can always find an unexpected way to expose it. Don’t underestimate hackers.
  • Is there a way to still have debug codes in the code base, while they won’t be compiled into the binary that’s gonna ship?

The Good for iOS Development

Objective-C uses preprocessor while in Swift it’s Compiler Control Statements

Swift preprocessor flags

  • DEBUG — default flag for debug build
  • RELEASE — default flag for release buildCS_DEBUG — custom flag
  • CS_DEBUG — custom flag
#if DEBUG || CS_DEBUG    // show some debug tools or sensitive data#elif RELEASE    // shippable features, or ignore this elif block#endif

The Question for Android Development

Usually, 2 approaches are used to check debug build with essential differences

  • BuildConfig.DEBUG corresponds to the debug selected from build variants
  • ApplicationInfo.FLAG_DEBUGGABLE corresponds to the settings in build.gradle

However, all of those codes will be compiled into the binary.

Android Build Variants should be used to handle this use case.

Use Case

  • From MainActivity, clicking a button navigates to Settings
  • For release build, the Settings page shows production-related settings.
  • For debug build, the Settings page shows debug related tools.

Step 1: specify sourceSets in build.gradle (:app)

Step 2: organize codes in debug/main/release respectively, I figure this could be a good practice of having this file structure

Step 3: Code MainActivity.kt, activity_main.xml, to show a button, with onClickListener starting SettingsActivity.

Step 4: Code SettingsActivity.kt, and build different UIs in the 2 activity_settings.xml, with release UI and debug UI.

Moment of Truth

  1. Run Debug Build

2. Run Release Build

  • to avoid the hassle of signing, in the app’s build.gradle set signingConfig to use the debug one

There might be a better way. Let me know your thoughts. Thanks!

--

--