Cancel AsyncTask after some time

后端 未结 5 463
别那么骄傲
别那么骄傲 2020-12-31 06:11

This could be a duplicate question but I did not find what I was looking for. I am calling an AsyncTask in the UI activity new LoadData().execute(); and in doI

5条回答
  •  渐次进展
    2020-12-31 06:48

    try this :

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

    Courtesy and for more details see this answer.

提交回复
热议问题