3.18 Android Support

Since Micronaut dependency injection is based on annotation processors and doesn’t rely on reflection, it can be used on Android when using the Android plugin 3.0.0 or above.

This allows you to use the same application framework for both your Android client and server implementation.

Configuring Your Android Build

To get started you must add the Micronaut annotation processors to the processor classpath using the annotationProcessor dependency configuration.

The Micronaut micronaut-inject-java dependency should be included in both the annotationProcessor and compileOnly scopes of your Android build configuration:

Example Android build.gradle

  1. dependencies {
  2. ...
  3. annotationProcessor "io.micronaut:micronaut-inject-java:1.3.7"
  4. compileOnly "io.micronaut:micronaut-inject-java:1.3.7"
  5. ...
  6. }

If you use lint as part of your build you may also need to disable the invalid packages check since Android includes a hard coded check that regards the javax.inject package as invalid unless you are using Dagger:

Configure lint within build.gradle

  1. android {
  2. ...
  3. lintOptions {
  4. lintOptions { warning 'InvalidPackage' }
  5. }
  6. }

You can find more information on configuring annotations processors in the Android documentation.

Micronaut inject-java dependency uses Android Java 8 support features.

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