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
dependencies {
...
annotationProcessor "io.micronaut:micronaut-inject-java:1.3.7"
compileOnly "io.micronaut:micronaut-inject-java:1.3.7"
...
}
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
android {
...
lintOptions {
lintOptions { warning 'InvalidPackage' }
}
}
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
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import io.micronaut.context.ApplicationContext;
import io.micronaut.context.env.Environment;
public class BaseApplication extends Application { (1)
private ApplicationContext ctx;
public BaseApplication() {
super();
}
@Override
public void onCreate() {
super.onCreate();
ctx = ApplicationContext.run(MainActivity.class, Environment.ANDROID); (2)
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { (3)
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
ctx.inject(activity);
}
... // shortened for brevity, it is not necessary to implement other methods
});
}
}
1 | Extend the android.app.Application class |
2 | Run the ApplicationContext with the ANDROID environment |
3 | To allow dependency injection of Android Activity instances register a ActivityLifecycleCallbacks instance |