android-asyncservice
android-asyncservice copied to clipboard
@ApplicationContext doesn't work with fragments.
Service field annotated with @ApplicationContext is null when injecting service into fragment.
Here's code from fragment:
@InjectService
PdfGeneratorService pdfGeneratorService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AsyncService.inject(this);
}
@Override
public void onDestroy() {
super.onDestroy();
AsyncService.unregister(this);
}
PdfGeneratorService:
@AsyncService
public class PdfGeneratorService {
@ApplicationContext
static Context context;
public File generateClassRecordsTable(List<Student> students) {
return new ClassTableCreator(context, students, context.getFilesDir()).create();
}
}
Further investigation lead me to AsyncService.java, and here's the code that supposed to get Application context from object.
/**
* If the given object contains an Android context, extract
* the application context and retain it statically.
*/
private static void extractContextFromObject(Object object) {
if (context == null && object instanceof Context) {
context = ((Context) object).getApplicationContext();
}
}
But fragments doesn't have context, so I need to have a way to pass some context while injecting into fragment. Maybe some kind of builder approach for this would be better for this?
As a workaround, have you tried using AsyncService.inject(this)
in your Application's onCreate
method? It should save the context from there.
Thanks, it works. But this way of initialization wasn't clear for me when I ran into this issue. Maybe it would be better to make some initialization method which will take Context or (maybe even better) Application?
Yep, exactly. I thought on the moment that it would work for most cases and then I forgot about it. I'll make one. Thanks for reporting.
Thank you for this lib, it's great!
Can you please give an example for that workaround?
public class YourApplication extends Application {
@Override
public void onCreate() {
AsyncService.inject(this);
}
}
Don't forget to declare this application class in your AndroidManifest.xml
.
Thanks a lot! Your work is appreciated :)