Reputation: 100358
I have a class UserManager
which handles creation and user sessions:
src/main/java/com/myapp/UserManager.java
:
public class UserManager {
public UserManager(){
if(BuildConfig.DEBUG){
createAndLogin("dummy", "dummy");
}
}
public void createAndLogin(String username, String password){
// Create and login logic
}
/* Some more methods */
}
As you can see, when in debug mode, I want to automatically login, so I don't need to do that manually each time I push the app to the development device.
I am wondering if I can do this more efficiently. I've tried to create a debug
folder, and copy the class. The new setup would be:
src/
main
/java/com/myapp/UserManager.java
:
public class UserManager {
public void createAndLogin(String username, String password){
// Create and login logic
}
/* Some more methods */
}
And:
src/
debug
/java/com/myapp/UserManager.java
:
public class UserManager {
public UserManager(){
createAndLogin("dummy", "dummy");
}
public void createAndLogin(String username, String password){
// Create and login logic
}
/* Some more methods */
}
Unfortunately, this is not allowed, as it complains about a duplicate class.
As mentioned here, you need productFlavors
to accomplish this. The setup in build.gradle
would be:
buildTypes {
debug {
debuggable true
signingConfig signingConfigs.debug
}
release {
debuggable false
signingConfig signingConfigs.release
}
}
productFlavors {
dev { }
prod { }
}
Now I have moved the two classes to src/prod/...
, and src/dev/...
, and deleted the class from src/main/...
.
This works, but I'm still not happy. I require a lot of duplicate code, and I'm not sure I'm using the productFlavors
as they should be used.
TL;DR
How can I use productFlavors
or something similar to easily login in development builds?
Upvotes: 1
Views: 105
Reputation: 80010
In my opinion, your first approach of doing:
if(BuildConfig.DEBUG){
createAndLogin("dummy", "dummy");
}
isn't that bad. It keeps all the code in one place. Having said that, your second approach of putting code in src/debug is close, and you don't need to use product flavors at all to go that way. Do this:
createAndLogin
version of UserManager
in src/debugUserManager
in src/releaseIf both versions of that class have a lot of common logic, then you could make each of them inherit from a common base class that you do put in src/main.
One disadvantage to this approach is that at present, Android Studio isn't smart enough to have code that's in flavors or build types other than the current one participate in important things like refactoring. What that means is that if you're currently working on the debug build type and you refactor UserManager
by, say, moving it to a different package, it won't refactor the copy in your release build type, and that will be orphaned until you go fix it up.
Upvotes: 3