Reputation: 327
I want with help of gradle build 2-3 different APKs where the app name changes and some lines of code. I don't want to change whole directories or whole files, only snippets of code, is this possible? I have tried to understand Build variants and Product flavor. but can't figure out how it works. Also this tutorial.
Thanks
Upvotes: 2
Views: 86
Reputation: 17085
This is just a suggestion. We faced the same thing and this is how we got it to work. In my opinion it's very clean and yes it does use product flavors.
So let's say you have a class Address, which is formatted differently from country to country, but of course has a lot of common code. For the sake of simplicity let's say you have only street_number
and street_name
, but on country A
the address should be formatted as street_number street_name
and on country B
it should be formatted as street_name, street_number
.
The way we did this was having a project structure like so:
src
|
|\ main
|\ countryA
|\ countryB
So the project has 2 flavors - countryA
and countryB
. Here's the relevant build.gradle
part:
productFlavors {
countryA {
applicationId "com.countryA"
}
countryB {
applicationId "com.countryB"
}
}
Now for the code part. So Address
is a common class which we placed inside main
and would look more or less like:
public abstract class AbstractAddress {
private String streetNumber;
private String streetName;
// ... your favorite getters and setters plus some common methods
public abstract String getFormattedAddress();
}
The key here is that the class is abstract and the sub-classes need to implement getFormattedAddress()
. Now in the countryA
folder you'd have:
package com.myapp.addresses;
public class Address extends AbstractAddress {
public String getFormattedAddress() {
return getStreetNumber() + " " + getStreetName();
}
}
Now in the same package as in countryA
but in countryB
's folder, you'd have the same class, but with a different implementation:
package com.myapp.addresses;
public class Address extends AbstractAddress {
public String getFormattedAddress() {
return getStreetName() + ", " + getStreetNumber();
}
}
Gradle will take care of generating the tasks for you. Something on the lines of assembleCountryA
and assembleCountryB
(It also depends on the build variants you have). Of course you can also generate all apks using only one task.
Upvotes: 3