How to use build types (debug vs release) to set d

2019-01-26 05:45发布

Background

On Android Studio, you can have different build types, each has its own configuration, similar to product-flavors (as shown here)

The problem

I wish that each time I have my app installed somewhere, I would immediatly know which type it was - release or debug, just by looking at it.

For this, I think I can use the build.gradle file :

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        debuggable true
    }
}

Thing is, I don't know what to put there. I want the app name to be different (and yet have the string in the strings files, as it's translated), and I want to set the style of something in the app to be different (for example, the color of the action bar).

I've found that I can use "resValue" (found about it here), but for some reason, no matter what I do, it won't compile:

  • If the resource was already declared (like in the app-name, which is translated), it says the resource is duplicated
  • If the resource wasn't declared, I can't reach it via code/xml.

The question

How do I use different resource values for the build types, even if they already exist?

2条回答
Fickle 薄情
2楼-- · 2019-01-26 05:57

How do I use different resource values for the build types, even if they already exist?

They already exist in the main sourceset. Add other sourcesets for your other build types of interest, where you override the resources you want.

For example, in this sample project I have a main sourceset and a debug sourceset. Both have the app_name string resource in res/values/strings.xml, but with different values. In a debug build, the debug sourceset version of the resource will be used; in any other build (e.g., release), the debug sourceset is ignored entirely, and the main sourceset version of the resource is used.

Note that I do not have a release sourceset. Particularly when overriding resources, this is perfectly fine -- you only need a sourceset for a build type when you want to change something for that build type, not for every build type that you are using.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-26 06:06

In File|Project Structure|app|Flavors we have:

Version Name: 1.3

In Strings resource file we have:

<string name="app_name">MyAppTitle</string>

In "onCreate" of MainActivity class:

...
//add version to application title
int versionCode = BuildConfig.VERSION_CODE; // unused in my application
String versionName = BuildConfig.VERSION_NAME;
this.setTitle(this.getTitle() + " v"+  versionName);
...

The result is "MyAppTitle v1.3"

查看更多
登录 后发表回答