Search code examples
androidgradleandroid-gradle-pluginandroid-productflavorsandroid-proguard

Android flavors with different dependencies and same class file


I have two different flavors of my Android app, lite and pro. In the app, I have a class called customFragment.java that is included in main (not different between flavors) and including also following code:

import haibison.android.lockpattern.LockPatternActivity;    

private void showLockPattern() {
    if (BuildConfig.IS_VERSION_PRO) {
        Intent intent = new Intent(LockPatternActivity.ACTION_VERIFY_CAPTCHA, null, this, LockPatternActivity.class);
        startActivityForResult(intent, PATTERN_ID);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PATTERN_ID && resultCode == Activity.RESULT_OK) {
        Log.i("App", "OK!");
    }
}

And in app.gradle I have included the LockPattern library only for the pro flavor:

dependencies {
    proCompile 'com.github.haibison:android-lockpattern:6.0.0'
}

The class that I described in the same for both flavors (so in main folder) since it's quite big and I don't want to duplicate the code in both flavors. The pro flavor builds successfully but the lite flavor shows an error since I don't import the dependency for the lite flavor as well.

One solution that I see would be to add the lockpattern library to both flavors but then using proGuard removing it from the lite flavor. Although I believe this might work, it's probably not the smoothest option. Of course I could also simply ignore the overhead of unused library in the lite flavor.

How would you tackle this problem? I've searched across stackoverflow for long time but have not found any answer, so for the first time in few years I had decided to register and ask the question.


Solution

  • Lite version is not compiling because java cannot find LockPatternActivity. For that thing you can use following solution.

    You need to have a class in flavor pro

    public final class LockPatternHelper {
        private LockPatternHelper() {}
    
        public static void showLockPattern() {
             Intent intent = new Intent(LockPatternActivity.ACTION_VERIFY_CAPTCHA, null, this, LockPatternActivity.class);
             startActivityForResult(intent, PATTERN_ID);
        }
    }
    

    In flavor lite it should be same class with empty method showLockPattern().

    public final class LockPatternHelper {
        private LockPatternHelper() {}
    
        public static void showLockPattern() {}
    }
    

    After this you can call LockPatternHelper.showLockPattern() from your customFragment.java

    Every flavor will use it's helper and lite version will not contain unnecessary library.