Android AsyncTask blocks back key dispatch Event

前端 未结 2 1708
广开言路
广开言路 2021-01-17 03:39

The Problem is:

My Activity starts an AsyncTask in onStart(). In the doInBackground Method I make a short webrequest, and depending on your network connetion, this m

相关标签:
2条回答
  • 2021-01-17 04:18

    when the user presses the back button during the doInBackground Method, the Keyevent is always dispatched AFTER my doInBackground method is finished.

    No, this isn't true.

    If I hit the BACK button on my device when an AsyncTask is running in my main Activity (downloading files from my server), the Activity is immediately closed.

    What IS true, however, is the AsyncTask will continue to run whatever code is in its doInBackground() method UNLESS I explicitly cancel it (but you kind of know that already).

    As far as I can tell, your 'webrequest' (whatever that may be) is blocking your doInBackground() method and because of that, any attempt to cancel it in onPause(), onStop, onDestroy() etc will never work.

    As advantej points out, the way the AsyncTask.cancel(...) method works is that it causes isCancelled to be set to 'true'. In order to successfully cancel the AsyncTask's doInBackground() method you need to periodically check isCancelled. Example...

    @Override
    protected Void doInBackground(String... params) {
    
        while (!isCancelled) {
            DoSomething();
        }
    }
    

    The problem is if DoSomething() (for example your 'webrequest') is blocking the while loop then isCancelled won't be checked until it completes.

    0 讨论(0)
  • 2021-01-17 04:24

    This is the expected behavior. The documentation says :

    Cancelling a task

    A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

    0 讨论(0)
提交回复
热议问题