我正在尝试在网络通话期间实现水平进度条更新。我用来进行网络调用的API仅需回调onSuccess和onFailure。完成大约需要0.5-3秒。
我的问题是,如何量化此类网络调用的进度以更新UI或具体说明我如何在AsyncTask的doInBackgropund实现内的publishProgress()方法中传递什么
最佳答案
不一定是进度的准确表示。仅当我可以填写它以向用户提供有关正在发生的事情的UI反馈时,这对我来说就足够了。
就个人而言,我仍将使用不确定的进度指示器。用户非常了解从应用程序开发人员那里检测到BS。
话虽这么说,您可以使用one of Zeno's paradoxes的变体:每500毫秒左右,将剩余的工作量减少一半。所以:
在时间索引0处,进度显示为0%(剩余100%)
在500ms的时间索引上,显示进度为50%(剩余50%)
在时间指标1000毫秒处显示进度为75%(剩余25%)
在时间索引1500毫秒时显示进度为87.5%(剩余12.5%)
等直到工作完成
您可能需要调整更新频率和削减量。但基本上,您会在整个工作中不断显示增量进度,直到完成API任务为止。与线性进度相反(例如,每500毫秒10%),使用此算法可以确保永远不会达到100%,因此始终有更多进步的余地。诚然,您最终会进入ProgressBar
... :-)中的亚像素调整。
要执行定期工作,最简单的事情是postDelayed()
“循环”,因为它不需要额外的线程:
/***
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,请注意,我的周期是5000ms,对于您的用例来说太长了)