Android 仅当耗时大于500毫秒时显示对话框
在自定义的Android 仅当耗时大于500毫秒时显示对话框,android,progressdialog,Android,Progressdialog,在自定义的AsyncTask中,我正在使用ProgressDialog,在耗时的任务完成后,将显示并隐藏一个加载对话框。有时任务可以很快完成,对话框会立即出现和消失,这对用户体验非常不利,是否有可能仅当消耗的时间大于某个时间段(例如500毫秒)时才显示对话框 public class MyTask extends AsyncTask<Void, String, Integer> { private ProgressDialog dialog; @Override prot
AsyncTask
中,我正在使用ProgressDialog
,在耗时的任务完成后,将显示并隐藏一个加载对话框。有时任务可以很快完成,对话框会立即出现和消失,这对用户体验非常不利,是否有可能仅当消耗的时间大于某个时间段(例如500毫秒)时才显示对话框
public class MyTask extends AsyncTask<Void, String, Integer> {
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(context, "", context.getString(R.string.loading) + "...");
}
@Override
public Integer doInBackground(Void... params) {
//time consuming task is here
}
@Override
protected void onPostExecute(Integer code) {
if (dialog != null) {
dialog.dismiss();
}
}
}
公共类MyTask扩展了AsyncTask{
私人对话;
@凌驾
受保护的void onPreExecute(){
dialog=ProgressDialog.show(context,“”,context.getString(R.string.load)+“…”;
}
@凌驾
公共整数doInBackground(Void…params){
//这是一项耗时的任务
}
@凌驾
受保护的void onPostExecute(整数代码){
如果(对话框!=null){
dialog.dismise();
}
}
}
如果您有任何建议,我们将不胜感激。您可以使用
处理程序在500毫秒后显示对话框。然后在onPostExecute
中取消处理程序的可运行程序(如果尚未运行)并隐藏对话框(如果已创建)
下面是一个例子:
public class MyTask extends AsyncTask<Void, String, Integer> {
private ProgressDialog dialog;
private Handler handler;
@Override
protected void onPreExecute() {
handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
dialog = ProgressDialog.show(context, "",
context.getString(R.string.loading) + "...");
}
}, 500);
}
@Override
public Integer doInBackground(Void... params) {
//time consuming task is here
}
@Override
protected void onPostExecute(Integer code) {
// Remove all runnables from queue
handler.removeCallbacksAndMessages(null);
// Hide dialog if one exists
if (dialog != null) {
dialog.dismiss();
}
}
}
公共类MyTask扩展了AsyncTask{
私人对话;
私人经办人;
@凌驾
受保护的void onPreExecute(){
handler=新的handler();
handler.postDelayed(新的Runnable(){
@凌驾
公开募捐{
dialog=ProgressDialog.show(上下文“”,
getString(R.string.load)+“…”;
}
}, 500);
}
@凌驾
公共整数doInBackground(Void…params){
//这是一项耗时的任务
}
@凌驾
受保护的void onPostExecute(整数代码){
//从队列中删除所有可运行项
handler.removeCallbacksAndMessages(null);
//隐藏对话框(如果存在)
如果(对话框!=null){
dialog.dismise();
}
}
}
如果您无法知道需要多长时间,也不知道平均时间,我建议您不要按照@user3249477的建议延迟对话,原因如下:
假设您的任务可能需要0到5000毫秒,并且几率是恒定的。在500毫秒之前完成任务的几率为10%。在500到1000毫秒之间完成任务的几率也为10%。500毫秒后显示一个对话框是无用的,它闪烁(立即消失)的几率与之前相同
我的建议是:了解平均时间,然后从那里开始。您可以在post execute中添加一个计时器,并在500毫秒(或您想要的时间)后关闭对话框。如果您只是想让用户有时间查看对话框。@SNt我想要的是,如果花费的时间小于500毫秒,就不要显示对话框。