Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change debug/release manifest key dynamically for each flavor

I am using one service where it's required to setup API key in AndroidManifest like this:

    <meta-data
        android:name="service_api_key"
        android:value="@string/my_api_key" />

The problem with this is that I have a couple of flavors of my app and I need to setup different API keys for each flavor. Each flavor needs to have different API key for debug and release:

flavor1
- debug key: key1
- release key: key2

flavor2
- debug key: key3
- release key: key4

flavor3
- debug key: key5
- release key: key6

What would be the recommended way to accomplish this?

like image 909
user4386126 Avatar asked Jan 21 '16 16:01

user4386126


3 Answers

What would be the recommended way to accomplish this?

Step #1: Create sourcesets for each build variant (src/flavor1Debug/, src/flavor1Release/, etc.) for which you need a different API key than whatever you have in src/main/.

Step #2: In each sourceset, have a res/values/strings.xml file that contains that build variant's value for my_api_key.

Step #3: Beer.

like image 163
CommonsWare Avatar answered Oct 13 '22 20:10

CommonsWare


not tested but I imagine you could try something like this...

applicationVariants.all {variants ->
variant.productFlavors.all { flavor ->
                flavorChoosed = " ${flavor.name}"
            }
        }
release {
            switch(flavorChoosed){
            case "flavor1":
            resValue "string", "flavorId", apiKeyRealeseFlavor1
            break
            .....
            }
        }

 debug{
   switch(flavorChoosed){
                case "flavor1":
                resValue "string", "flavorId", apiKeyDebugFlavor1
                break
                .....
      }
} 
 <meta-data
        android:name="service_api_key"
        android:value="${flavorId}" />
like image 30
Pedro Teran Avatar answered Oct 13 '22 22:10

Pedro Teran


For each Product Flavor you have added to your gradle file you should add a string.xml resource file for values.

When you switch your build variant, Android studio will be smart enough to grab the matching value for your build.

If you dont specify one, then it defaults to the main one.

EDIT:

enter image description here

Then for the source set, select the release or debug version of your productFlavor:

enter image description here

like image 33
meda Avatar answered Oct 13 '22 21:10

meda