You should inject the AsyncTask
into MyFragment
rather than using "new MyTask(..)". The MyTask
constructor should take an UserApi
instance and a Context
object which can be provided by the module with code akin to;
/**
* The application module.
*
* @param context The context.
*/
public MyModule(final Context context) {
this.context = context.getApplicationContext();
}
/**
* Provides context.
*
* @return the application context.
*/
@Provides @Singleton Context provideContext() {
return context;
}
Your fragment code should then look like;
public class MyFragment extends Fragment {
@Inject Provider<MyTask> myTaskProvider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inject(this);
myTaskProvider.get().execute();
}
}
And your AsyncTask API should be;
@Inject
public MyTask(Context context, UserApi userApi) { }
Notice I used a Provider
for the injection of the AsyncTask. This is necessary to avoid exceptions akin to "You can only execute a task once" that you would get if you called execute
against the same AsyncTask object more than once. You then register MyFragment
under your module injects = { }
annotation arguments.