[英]Display ProgressDialog until AsyncTask finishes, then update UI
这是我的应用程序的流程:
1)用户拍照或录像
2)媒体已保存到内部存储器
3)路径已分配给自定义对象
4)更新UI以指示用户可以继续
仅当自定义对象具有图像路径或视频路径时,UI才会更新。 我刚开始使用AsyncTask
在后台线程中保存到内部存储,因此应用程序在保存大文件时不会挂起,但我遇到了一些问题。
我想做的事:在doInBackground()
完成之前显示ProgressDialog
,然后将路径分配给我的Object, 然后继续在主线程上更新UI。
现在,主线程将在AsyncTask
仍在工作时继续,并且UI将无法正确更新,因为路径尚未分配给Object。
我读过有关AsyncTask#get()
,但我不确定如何使用ProgressDialog
实现它。 我试过了,主线程似乎并没有等待结果再继续。
我真的很感激任何帮助。 谢谢!
我的AsyncTask
:
private class SaveMediaTask extends AsyncTask<Integer, Void, String>
{
private ProgressDialog progressDialog;
private int mediaType;
public SaveMediaTask()
{
progressDialog = new ProgressDialog(getActivity(), ProgressDialog.THEME_HOLO_LIGHT);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
this.progressDialog.setTitle("Processing");
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
this.progressDialog.show();
}
protected String doInBackground(Integer... mediaType)
{
//save to internal storage and return the path
return path;
}
protected void onPostExecute(String path)
{
//by the time this runs, the UI has already tried to update itself on the main thread,
//and found that myObject does not yet have a path. Once this runs, it is too late.
myObject.setPath(path);
if (progressDialog.isShowing())
{
progressDialog.dismiss();
}
}
}
用户离开相机后立即如何调用它:
new SaveMediaTask().execute(MEDIA_TYPE_IMAGE);
//WAIT HERE AND DISPLAY PROGRESSDIALOG UNTIL TASK IS DONE
//update UI
您的onPostExecute
应该通知您的活动,该活动可以继续。 所以基本上:
// Start the task from your activity
new SaveMediaTask().execute(MEDIA_TYPE_IMAGE);
// Method that will be called when task is completed
public void taskComplete() {
// update UI
}
...
protected void onPostExecute(String path) {
myObject.setPath(path);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
((YourActivity)getActivity()).taskComplete();
}
您可以将标记为//update UI
代码移动到onPostExecute
方法的末尾。 onPostExecute
总是在UI线程上调用,是更新UI以反映AsyncTask
工作结果的好地方。
主线程似乎没有等待结果再继续。
主线程不会等待。 这不是AsyncTask
工作方式。 AsyncTask
与您的主线程一起在后台运行。
然后继续在主线程上更新UI。
完成AsyncTask
任务后,您不需要继续主线程来更新UI,您可以在解除progressDialog
之后简单地在onPostExecute()
执行该帖子 doInBackground
任务,即progressDialog.dismiss();
因为onPostExecute
在UI线程中运行。
此外,好的方法是在onPreExecute()
方法中启动progressDialog
并在onPostExecute
其关闭,而不检查progessDialog
是否仍然显示,因为onPostExecute()
只有在doInBackground()
方法完成其工作时才会运行。
我想做的事:在doInBackground()完成之前显示ProgressDialog,然后将路径分配给我的Object,然后继续在主线程上更新UI。
onPreExecute
启动ProgressDialog, doInBackground
指定对象的路径 onPostExecute
关闭ProgressDialog, onPostExecute
工作,因为它在UI线程中运行。 您还可以通过调用publishProgress()
在doInBackground
仍在运行时更新UI线程。 每次调用此方法都将触发UI线程上onProgressUpdate()
的执行。
提示:它是一个好主意,驳回progressDialog
内onCancelled()
方法贬在旁边onPostExecute()
的情况下,如果你取消里面你的任务doInBackground
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.