如何使用AndroidAnnotations取消@Background任务

时间:2013-03-13 10:07:00

标签: android-annotations

我的用例是,只要用户输入EditText,输入数据就会用于在后台执行操作。这些操作可能需要足够长的时间才能导致ANR。 @TextChange与@Background一起工作正常,如果操作足够快。但是操作需要足够长的时间,以便用户输入更多数据,我将得到线程问题,因为将有多个后台任务将命令更新相同的UI组件。

我认为我使用AsyncTask API实现了所需的行为,但也想寻找基于AndroidAnnotations的解决方案,因为它简化了代码。顺便说一句好书。

下面是一些代码片段,希望能够说明我的观点。感谢至少阅读,评论/答案赞赏:)

@TextChange
void onUserInput(...) {
  // This will start a new thread on each text change event
  // thus leading to a situation that the thread finishing
  // last will update the ui
  // the operation time is not fixed so the last event is
  // not necessary the last thread that finished
  doOperation()
}

@Background
void doOperation() {
  // Sleep to simulate long taking operation
  Thread.sleep( 6000 );
  updateUi()
}

@UiThread
void updateUi() {
  // Update text field etc content based on operations
}

更新:目前无法做到这一点,请参阅下面的DayS答案。

2 个答案:

答案 0 :(得分:4)

从AA 3.0开始就有可能。阅读此thread

@Override
protected void onStop() {
    super.onStop();
    boolean mayInterruptIfRunning = true;
    BackgroundExecutor.cancelAll("longtask", mayInterruptIfRunning);
}

@Background(id="longtask")
public void doSomethingLong() {
    // ...
}

答案 1 :(得分:1)

已经有this kind of request on Android Annotations但已关闭,因为没有提出任何解决方案。但如果您对此有任何了解,请继续并重新打开此问题;)