Launching a long running task from an AlertDialog (Android)

半世苍凉 提交于 2019-12-11 16:53:21

问题


I have an AlertDialog in and it's got a button, which, if selected, will initiate a file upload to a remote server like this:

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

This works fine, the only problem is that uploadFile() can potentially take a long time (30 seconds to 2 minutes). I would like to replace the AlertDialog with a progress dialog (even an indeterminate one), but I can't see how to launch one dialog from another?

Can anyone offer some advice for a how I could accomplish this.

Thanks, Jarabek


回答1:


You can use AsyncTask here, keep your ProgressDialog on the PreExecute() and call the method in the doingInBackground() and dismiss the ProgressDialog in the PostExecute().

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;
        }
    }

Then just call the MyAsyncTask using new MyAsyncTask().execute();




回答2:


The best way to do this - using AsyncTask. There you can provide progress and do your long action



来源:https://stackoverflow.com/questions/8515377/launching-a-long-running-task-from-an-alertdialog-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!