从AlertDialog(Android)启动长时间运行的任务

时间:2011-12-15 05:06:21

标签: android task alertdialog

我有一个AlertDialog并且它有一个按钮,如果选择该按钮,将启动文件上传到远程服务器,如下所示:

builder.setMessage(text)                
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
uploadFile();
}})

这很好用,唯一的问题是uploadFile()可能需要很长时间(30秒到2分钟)。我想用进度对话框(甚至是一个不确定的对话框)替换AlertDialog,但我看不到如何从另一个对话框启动一个对话框?

任何人都可以就如何实现这一目标提供一些建议。

谢谢, Jarabek

2 个答案:

答案 0 :(得分:5)

您可以在此使用AsyncTask,将ProgressDialog保留在PreExecute()上,然后调用doingInBackground()中的方法并关闭PostExecute(). <中的ProgressDialog / p>

private class MyAsyncTask extends AsyncTask<Void, Void, Void>
    {

        ProgressDialog mProgressDialog;
        @Override
        protected void onPostExecute(Void result) {
            mProgressDialog.dismiss();
        }

        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(ActivityName.this, "Loading...", "Data is Loading...");
        }

        @Override
        protected Void doInBackground(Void... params) {
            uploadFile();
            return null;
        }
    }

然后使用MyAsyncTask

调用new MyAsyncTask().execute();

答案 1 :(得分:1)

执行此操作的最佳方式 - 使用AsyncTask。在那里,您可以提供进步并做长时间的行动