0

In Main UI:

  • Create a dialog without a cancel button
  • Start AsyncTask which in turn starts a HttpURLConnection in the doInBackground()
  • After about 10 seconds the following is started in the Main UI thread via a postDelayed Runnable

    Check if the Dialog has been cancelled, which would indicate a finished HttpURLConnection/doInBackground()

    If it is not cancelled, add a cancel button with a oncancelcallback to the dialog, and the oncancelcallback will trigger some code which should be able to cancel the HttpURLConnection.

    My problem is that while the AsyncTask is running its doInBackground(), when the cancel button appears on in the dialog and is pressed, the oncancelcallback won't excute its code while the doInBackground() is still doing its HttpURLConnection stuff. It will wait for the doInBackground() to finish and then execute its code, which obviates its purpose.

Daniel F
  • 13,684
  • 11
  • 87
  • 116
  • Please post your codes. – frogatto Feb 17 '16 at 18:57
  • `doInBackground` is run on a different thread than the UI so the cancel callback will be executed regardless of what `doInBackground` does. How do you try to stop the AsyncTask? – StenSoft Feb 17 '16 at 18:58
  • @HiI'mFrogatto I'd love to, but this is a lot of code spread among multiple files. To me it's not worth the effort to create a code-summary for this purpose. I've now even dumped the cancel functionality completely, but I'll still track this question for future reference. – Daniel F Feb 17 '16 at 19:02
  • @StenSoft It is not yet clear how I can cancel the `AsyncTask`, currently, just for checking what works, I'm placing the `HttpURLConnection` into a global variable on which I then call `_global_connection.disconnect()` in the `oncancelcallback`. But when I check the the value of `_global_connection`, it's already null, which is the result of disconnect already having been called in the `doInBackground()` (I set it to null after that disconnect). – Daniel F Feb 17 '16 at 19:06
  • You can't use a variable from two threads at the same time. That has undefined behaviour. To cancel an AsyncTask, call it's method `cancel` and check for `isCancelled` in `doInBackground`. – StenSoft Feb 17 '16 at 19:09
  • I'm trying to cancel a single, possibly long-running `HttpURLConnection`. That would require me to be able to poll for `isCancelled`, which I can't do since the `HttpURLConnection` will be blocking the `doInBackground`. Or am I understanding this wrong? – Daniel F Feb 17 '16 at 19:12
  • You can call `cancel(true)` to interrupt all IO. It will throw `InterruptedException` in that case. But you should still check for `isCancelled` if you are e.g. processing large amounts of data. – StenSoft Feb 17 '16 at 19:19
  • @StenSoft Thanks, I'll try that, but don't have time ATM. I'll post back later. – Daniel F Feb 17 '16 at 19:46

0 Answers0