Ideal way to cancel an executing AsyncTask

前端 未结 9 2126
不思量自难忘°
不思量自难忘° 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:59

    The thing is that AsyncTask.cancel() call only calls the onCancel function in your task. This is where you want to handle the cancel request.

    Here is a small task I use to trigger an update method

    private class UpdateTask extends AsyncTask {
    
            private boolean running = true;
    
            @Override
            protected void onCancelled() {
                running = false;
            }
    
            @Override
            protected void onProgressUpdate(Void... values) {
                super.onProgressUpdate(values);
                onUpdate();
            }
    
            @Override
            protected Void doInBackground(Void... params) {
                 while(running) {
                     publishProgress();
                 }
                 return null;
            }
         }
    

提交回复
热议问题