I have a 3rd party library that exposes its functionality through a listener interface. The requirement of the library is that it gets initialized in the onCreate of the custom Android Application class.
public class CustomApplicationWithListener extends Application implements ThirdPartyListener {
public void onCreate() {
if(feature.isTurnedOn()){
// the library requires an application instance of type ThirdPartyListener
init(this);
}
}
}
I was trying to hide this functionality behind a feature flag and was wondering if there is a way to abstract the listener from the application class and only define it when the feature is needed. Only then we declare that interface. I know the custom application class needs to be defined in the manifest. Is there a way to dynamically decide at runtime that if the feature is enabled then initialize the base custom application object with the third party listener something like below and let the main manifest know the version we are going to use?
var application: Application?
if(feature.isTurnedOn()){
application = CustomApplicationWithListener()
} else {
application = CustomApplication
}
Code generation to be done in android application at runtime is not an easy task and would be done with
Reflection. Take a look at Java's Reflection API to understand how reflection works.On the other hand, compiler time codegen is rather not that hard an can be achieved by
Annotation Processors. Refer to this blogpost to understand how annotation processors work.Take a look at Dynamic Modules which allow users to download specific features on demand. This may be the most adept solution to your case. Setting up a PreferenceFragment having feature flag views and reading the value through SharedPreferences in a solution.
I still question why you do not want to declare the 3rd party library in your class application. A lot of 3rd party libraries often required instantiation in the base application class. If library dependency is your answer, then that can be solved by splitting up own application into presentation, data and domain module. This will at least isolate the android framework from your business logic.