0

假设我有一个 Android 启动的服务,它执行一些任务,例如:

-服务开始

- 执行任务 A,执行任务 B,然后下载文件 1,下载文件 2,最后执行任务 C。

-服务停止

假设当服务执行任务 B 时,一个活动绑定到它。检查服务当前正在执行什么任务以更新活动 UI 的正确方法是什么?

我现在正在做的方式是在进程中为每个任务创建一个布尔标志,然后当活动绑定到服务时,它检查哪个标志为真以向活动发送正确的回调。它可以工作,但是随着任务的增加,当错误发生时它会变得更加复杂甚至更加困难。

private boolean doingTaskA = false;
private boolean doingTaskB = false;
.
.

public void doTaskA() {
   // Task started, set the flag to true.
   doingTaskA = true;
   // send callback to update activity UI.
   callback.onDoingTaskA();
   // doing some API calls that takes some time to retrieve information
   ...
   // Task finished, set to false.
   doingTaskA = false;
}
public void doTaskB() {
   // Task started, set the flag to true.
   doingTaskB = true;
   // send callback to update activity UI.
   callback.onDoingTaskB();
   // doing some API calls that takes some time to retrieve information
   // while doing in background, an activity binds to this service (assuming 
   // not already bound).
   ...
   // Task finished, set to false.
   doingTaskB = false;
}

public IBinder onBind(Intent intent) {
  // when binding check to see what the service is doing.
  if(doingTaskA){
    // send callback to update activity UI.
    callback.onDoingTaskA();
  }
  if(doingTaskB){
    // send callback to update activity UI.
    callback.onDoingTaskB();
  }
  ...
}

请帮助我以有效和可靠的方式做到这一点。

谢谢!

4

0 回答 0