我正在尝试在网络呼叫期间实施水平进度条更新。我用来进行网络调用的API只需要回调onSuccess和onFailure。完成需要0.5到3秒左右的时间。
我的问题是,我如何量化这种网络调用的进度以更新我的UI或具体说明我在AsyncTask的doInBackgropund实现中的publishProgress()方法内部传递了什么
答案 0 :(得分:1)
它不一定是进展的准确表示。只有当我能填充它以向用户提供有关正在发生的事情的UI反馈时,这对我来说应该足够了。
就个人而言,我仍然使用无限期进度指标。用户非常精通从应用开发者那里检测BS。
话虽如此,您可以使用one of Zeno's paradoxes的变体:每500毫秒左右,将剩余的工作百分比减半。所以:
您可能需要调整更新频率和要削减的金额。但基本上,您将继续在整个工作中显示渐进的进度,直到您的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,请注意我的期限是5000毫秒,这对您的用例来说太长了)