Android Studio, somewhat predictably, allows two deployment modes debug and release. Configuring this in gradle allows you to configure certain options like if we should use proguard or not and what signing config to use. However this can be taken further to allow customization of certain java files based on release or debug build.
I’m not talking here about flavours, which is something slightly different. What I want to do is use one java class for debug and a different one for a release build. This allows me to suppress some debugging functions on a release build.
1. Create a Simple Project
1. Create a Simple Project
First I create a new project and quickly setup a simple MainActivity with a button to launch a SecondActivity. I’m going to keep these activities very simple just to prove the concept. Don’t create the SecondActivity yet, we’ll do it in the next step.
2. Create Build Types
First update your app/build.gradle file to reflect the following, note the buildTypes:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.example.android.myapplication"
minSdkVersion 10
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
signingConfigs {
debug {
storeFile file("--path-to-debug-keystore--")
}
release {
storeFile file("--path-to-release-keystore--")
storePassword "--password--"
keyAlias "--alias--"
keyPassword "--password--"
}
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
signingConfig signingConfigs.release
}
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
signingConfig signingConfigs.debug
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
}
3. Create folder structure
Create release and debug folders inside src. Inside both create a java folder, one (normally debug) will go blue and allow you to create a package. Create a new package matching your default package. In the other (normally release) you’ll have to just create folders instead of a package. Now create a SecondActivity.java in both. As the image below shows, you'll never get both release and debug to be correctly marked as a package. However when you switch using the build variants tab, you'll see the currently selected one change.
4. Test
Now you’re setup to configure your second activity as you wish, in my example I had each update a textview to say debug or release. Open the Build Variants tab in Android Studio and switch between build variants. This allows you to toggle the modes and release as such.
No comments:
Post a Comment