Skip to content
This repository has been archived by the owner on Feb 26, 2023. It is now read-only.

BackgroundTasksAndActivityBinding

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:

@EActivity
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
   */
  @NonConfigurationInstance
  @Bean
  MyBackgroundTask task;

  @Click
  void myButtonClicked() {
    task.doSomethingInBackground();
  }

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

}

Then the task itself:

@EBean
public class MyBackgroundTask {

  @RootContext
  MyActivity activity;

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

    updateUI(result);
  }

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

Using AndroidAnnotations

Questions?

Enjoying AndroidAnnotations

Improving AndroidAnnotations

Extending AndroidAnnotations

Clone this wiki locally