NonConfigurationInstance - PerfectCarl/androidannotations GitHub Wiki
Since AndroidAnnotations 2.5
When a configuration change occurs, your activities are usually destroyed and recreated. This behavior is great to reload resources, but you usually need to transfert references to extensive states (loaded bitmaps, network connections, actively running threads...) from the old to new activity instance.
That's what Activity.onRetainNonConfigurationInstance() is for (see RetainingAnObject). Using this method requires casting from Object
, and can be cumbersome when you have multiple objects.
@NonConfigurationInstance
Annotate your activity fields with @NonConfigurationInstance
to retain instances that are intensive to compute, on configuration changes.
public class MyActivity extends Activity {
@NonConfigurationInstance
Bitmap someBitmap;
@NonConfigurationInstance
@Bean
MyBackgroundTask myBackgroundTask;
}
Caution: while you can annotate any field, you should never annotate a field that is tied to the
Activity
, such as aDrawable
, anAdapter
, aView
or any other object that's associated with aContext
. If you do, it will leak all the views and resources of the original activity instance. Leaking resources means that your application maintains a hold on them and they cannot be garbage-collected, so lots of memory can be lost.
This caution doesn't apply to beans annotated with
@Bean
, because AndroidAnnotations automatically takes care of rebinding their context.