网络通话期间进度条更新

Progress bar update during a network call

我正在尝试在网络调用期间实现水平进度条更新。我用来做网络调用的API只需要回调onSuccess和onFailure。大约需要 0.5 - 3 秒才能完成。

我的问题是,我如何量化此类网络调用的进度以更新我的 UI 或者具体地说,我在 AsyncTask[=10 的 doInBackgropund 实现中的 publishProgress() 方法中传递了什么=]

It doesn't have to be the accurate representation of the progress. Only if i can fill it to give a UI feedback to the user that something is happening, that should be enough for me.

就个人而言,我仍然会使用不确定的进度指示器。用户非常精通检测来自应用程序开发人员的 BS。

也就是说,您可以使用 one of Zeno's paradoxes 的变体:每 500 毫秒左右,将剩余的工作百分比减半。所以:

  • 在时间索引 0 处,进度显示为 0%(剩余 100%)
  • 在时间索引 500 毫秒处,显示进度为 50%(剩余 50%)
  • 在时间索引 1000 毫秒时,显示进度为 75%(剩余 25%)
  • 在时间索引 1500 毫秒处,显示进度为 87.5%(剩余 12.5%)
  • 等直到工作完成

您可能需要调整更新频率和削减量。但基本上你会在整个工作过程中不断显示渐进的进展,直到你的 API 东西完成。与线性进展(例如,每 500 毫秒 10%)相反,此算法保证您永远不会 相当 达到 100%,因此始终有更多进步的空间。不可否认,您最终会在 ProgressBar... :-)

中进行亚像素调整

做周期性的工作,最简单的是postDelayed()"loop",因为它不需要额外的线程:

/***
  Copyright (c) 2012 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  From _The Busy Coder's Guide to Android Development_
    https://commonsware.com/Android
 */

package com.commonsware.android.post;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class PostDelayedDemo extends Activity implements Runnable {
  private static final int PERIOD=5000;
  private View root=null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    root=findViewById(android.R.id.content);
  }

  @Override
  public void onResume() {
    super.onResume();

    run();
  }

  @Override
  public void onPause() {
    root.removeCallbacks(this);

    super.onPause();
  }

  @Override
  public void run() {
    Toast.makeText(PostDelayedDemo.this, "Who-hoo!", Toast.LENGTH_SHORT)
         .show();
    root.postDelayed(this, PERIOD);
  }
}

(来自 this sample app,注意我的周期是 5000 毫秒,这对你的用例来说太长了)