One thing to know with Android is that you do not instantiate your own activities, it is the system which does.
Because of this, you cannot use constructor injection with activities. However, you can use attribute injection, which is cleaner IMO.
Extending the RoboActivity
class is the easiest way to use injection with Activity
.
RoboGuice provides similar classes for other Android components (RoboFragment
, RoboService
, etc.)
public class MyActivity extends RoboActivity {
@Inject
ITest test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// You can now use your test instance
}
}
All attribute with the @Inject
will be instantiated after super.onCreate(savedInstanceState);
is called.
With POJO (Plain Old Java Object), you have more options:
Attribute injection
public class Test {
@Inject
private Service1 service1;
@Inject
private Service2 service2;
public Test() {
}
}
Constructor injection
public class Test {
private Service1 service1;
private Service2 service2;
@Inject
public Test(Service1 service1, Service2 service2) {
this.service1 = service1;
this.service2 = service2;
}
}
Note that your constructor must have the @Inject
annotation if it has arguments.
You need this line <application ... android:name="com.example.project2.IOCApplication">
to tell the system that you are using an extended Application
class. Without it, Android will use the base class.
I encourage you to read the official documentation for more information.