DayS edited this page Apr 26, 2013 · 4 revisions

Since AndroidAnnotations 2.5

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:

public class MyActivity extends Activity {

  /* Using @NonConfigurationInstance on a @Bean will automatically 
   * update the context ref on configuration changes,
   * if the bean is not a singleton
  MyBackgroundTask task;

  void myButtonClicked() {

  void showResult(MyResult result) {
    // do something with result


Then the task itself:

public class MyBackgroundTask {

  MyActivity activity;

  void doSomethingInBackground() {
    // do something
    MyResult result = XXX;


  // Notice that we manipulate the activity ref only from the UI thread
  void updateUI(MyResult 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.

14/10/2018 The 4.5.1 release is out !

Using AndroidAnnotations


Enjoying AndroidAnnotations

Improving AndroidAnnotations

Extending AndroidAnnotations

Clone this wiki locally
You can’t perform that action at this time.
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.
Press h to open a hovercard with more details.