Ideal way to cancel an executing AsyncTask

前端 未结 9 2201
不思量自难忘°
不思量自难忘° 2020-11-22 05:54

I am running remote audio-file-fetching and audio file playback operations in a background thread using AsyncTask. A Cancellable progress bar is sh

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 06:38

    Just discovered that AlertDialogs's boolean cancel(...); I've been using everywhere actually does nothing. Great.
    So...

    public class MyTask extends AsyncTask {
    
        private volatile boolean running = true;
        private final ProgressDialog progressDialog;
    
        public MyTask(Context ctx) {
            progressDialog = gimmeOne(ctx);
    
            progressDialog.setCancelable(true);
            progressDialog.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    // actually could set running = false; right here, but I'll
                    // stick to contract.
                    cancel(true);
                }
            });
    
        }
    
        @Override
        protected void onPreExecute() {
            progressDialog.show();
        }
    
        @Override
        protected void onCancelled() {
            running = false;
        }
    
        @Override
        protected Void doInBackground(Void... params) {
    
            while (running) {
                // does the hard work
            }
            return null;
        }
    
        // ...
    
    }
    

提交回复
热议问题