目录(?)[+]
BackgroundTasksAndActivityBinding
Since AndroidAnnotations 2.5
Like an AsyncTask, @Background
does not handle any lifecycle changes on your activities.和AsyncTask类似, @Background
不会处理任何activity生命周期变化。
@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.
@Background
方法,然后屏幕发生了旋转,那么
@Background
代码将会执行到,无论如何,在这个实例上,它会被调用。
@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.
@Background
加在属于activity的方法上,依次调用一个
@UiThread
方法,这里就有一点点的风险,假如一个配置改变事件发生时,这个
@UiThread
方法可能在错误的实例中被调用。
AsyncTask
, keep references to those tasks in
onRetainNonConfigurationInstance()
, and rebind them to the new activity after a config change.
AsyncTask
,在
onRetainNonConfigurationInstance()
中保持对这些任务的引用,在配置改变后将它们重新绑定到新的activity上。
AndroidAnnotations provides @NonConfigurationInstance
, which can be combined with@EBean
,@Bean
,and @Background to achieve the same effect.AA提供了@NonConfigurationInstance
注解,结合@EBean
,@Bean
和 @Background
来达到这个效果。
Here is an example, first of all the activity:下面是例子,首先是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@BeanMyBackgroundTask task;@Clickvoid myButtonClicked() { task.doSomethingInBackground();}void showResult(MyResult result) { // do something with result}}
Then the task itself:然后是任务本身:
@EBean public class MyBackgroundTask { @RootContextMyActivity activity;@Backgroundvoid doSomethingInBackground() { // do somethingMyResult result = XXX;updateUI(result);}// Notice that we manipulate the activity ref only from the UI thread@UiThreadvoid 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.我们可能会提供更好的解决方案,但是这里面有很多不同的用例,我们需要全部考虑到。所以目前为止,@Background
只有非常简单的行为,短期内不会改变。但是,我们会介绍新的注解,它有更高级的 "thread + lifecycle"行为。
本文档的简单示例下载