当前位置: 代码迷 >> 综合 >> AndroidAnnotations——BackgroundTasksAndActivityBinding后台任务和activity绑定
  详细解决方案

AndroidAnnotations——BackgroundTasksAndActivityBinding后台任务和activity绑定

热度:58   发布时间:2023-12-11 23:58:00.0

AndroidAnnotation

目录(?)[+]

BackgroundTasksAndActivityBinding

Since AndroidAnnotations 2.5

Like an AsyncTask, @Background does not handle any lifecycle changes on your activities.和AsyncTask类似, @Background 不会处理任何activity生命周期变化。

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.
举个例子,假如你调用一个   @Background 方法,然后屏幕发生了旋转,那么   @Background 代码将会执行到,无论如何,在这个实例上,它会被调用。

If  @Background is placed on a method that belongs to the activity, and in turns call a  @UiThreadmethod, 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 方法可能在错误的实例中被调用。

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.
在Android中,优先于Loaders,通常处理这种情况的办法是使用 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"行为。


本文档的简单示例下载


  相关解决方案