You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Like an AsyncTask, @Background does not handle any lifecycle changes on your activities.
For instance, if you call an @Background method and then the screen is rotated, then the @Background code will be executed, no matter what, on the instance it was called on.
If @Background is placed on a method that belongs to the activity, and in turns call a @UiThread method, there is a risk that the @UiThread method will be called on the wrong activity instance, if a configuration change occurred.
In Android, prior to Loaders, the usual way to handle that was to use an AsyncTask, keep references to those tasks in onRetainNonConfigurationInstance(), and rebind them to the new activity after a config change.
AndroidAnnotations provides @NonConfigurationInstance, which can be combined with @EBean, @Bean and @Background to achieve the same effect.
Here is an example, first of all the activity:
@EActivitypublicclassMyActivityextendsActivity {
/* Using @NonConfigurationInstance on a @Bean will automatically * update the context ref on configuration changes, * if the bean is not a singleton */@NonConfigurationInstance@BeanMyBackgroundTasktask;
@ClickvoidmyButtonClicked() {
task.doSomethingInBackground();
}
voidshowResult(MyResultresult) {
// do something with result
}
}
Then the task itself:
@EBeanpublicclassMyBackgroundTask {
@RootContextMyActivityactivity;
@BackgroundvoiddoSomethingInBackground() {
// do somethingMyResultresult = XXX;
updateUI(result);
}
// Notice that we manipulate the activity ref only from the UI thread@UiThreadvoidupdateUI(MyResultresult) {
activity.showResult(result);
}
}
We could probably provide even better solutions, but there are a lot of different use cases, and we need to think about them all. So right now, @Background has a very simple behavior and this is not going to change. We could, however, introduce new annotations with an advanced "thread + lifecycle" behavior.