Enabling Dependency Injection

Once you have configured the classpath correctly, the next step is start the ApplicationContext.

The following example demonstrates creating a subclass of android.app.Application for that purpose:

Example Android Application Class

  1. import android.app.Activity;
  2. import android.app.Application;
  3. import android.os.Bundle;
  4. import io.micronaut.context.ApplicationContext;
  5. import io.micronaut.context.env.Environment;
  6. public class BaseApplication extends Application { (1)
  7. private ApplicationContext ctx;
  8. public BaseApplication() {
  9. super();
  10. }
  11. @Override
  12. public void onCreate() {
  13. super.onCreate();
  14. ctx = ApplicationContext.run(MainActivity.class, Environment.ANDROID); (2)
  15. registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { (3)
  16. @Override
  17. public void onActivityCreated(Activity activity, Bundle bundle) {
  18. ctx.inject(activity);
  19. }
  20. ... // shortened for brevity, it is not necessary to implement other methods
  21. });
  22. }
  23. }
1Extend the android.app.Application class
2Run the ApplicationContext with the ANDROID environment
3To allow dependency injection of Android Activity instances register a ActivityLifecycleCallbacks instance