如何在后台线程更新时处理进度条状态

时间:2015-02-27 09:32:50

标签: android

这是一个简单的场景:

  1. 你可以在一个单独的线程中开始一些背景,比如网络操作。
  2. ProgressBar设为可见。
  3. 在网络运营完成之前离开您的应用。
  4. 当您的应用程序处于后台时,网络操作已完成但您从未收到回调(或已触发事件),因为您应取消订阅回调/事件订阅以防止意外异常(您只能从主线程修改UI视图)。
  5. 即使您的后台操作已经完成,您也可以恢复应用并在屏幕上看到ProgressBar
  6. 我很好奇处理这种情况的最佳方法是什么。

3 个答案:

答案 0 :(得分:1)

一个可能的选项也可能是使用事件总线(例如https://github.com/greenrobot/EventBus)并在网络操作完成时保持粘滞事件并在onResume中检查您的活动。

答案 1 :(得分:0)

我的回答是ServiceIntentService。当您的应用程序处于后台时,我假设您隐藏了进度条。当应用程序位于前台时您可以绑定到Service的实例,可能有一个返回当前进度的方法。如果进度更大或等于最大值,则再次显示进度,否则您将采取其他措施

答案 2 :(得分:0)

这类场景的一般模式(也可包括数据处理,视图更新等)是:

/*
  `controller` is the object with reference to the task
  currently being executed.
  It can be anything:
      a network operation, 
      a file copy, 
      an image processing, 
      an asset loading, etc, etc...
*/

public void onStart() {
   super.onStart();
   myView.setSomeProperty(controller.getCurrentValue());
   controller.subscribe(this);
}

public void onStop() {
   controller.unsubscribe(this);
   super.onStop();
}

@Override
public void onControllerSubscriptionUpdate(int newValue){
   myView.setSomeProperty(newValue);
}

这样,每当Activity或Fragment到达前台时,您的视图都会使用最新参数进行更新。

相关问题