Cannot cancel running AsyncTask in AsyncTaskLoader

前端 未结 2 1263
天命终不由人
天命终不由人 2021-01-03 16:36

I want to cancel running AsyncTask (in AsyncTaskLoader) when the user clicks the home button. Here is what I created so far:

package cz.davidliska.android.lo         


        
相关标签:
2条回答
  • 2021-01-03 17:02

    If you mean "Is there any chance to cancel running AsyncTask in android.content.AsyncTaskLoader?" the answer is yes: you just need to add some "cancel points" in your loadInBackground method and check whether a cancellation request has been issued (isLoadInBackgroundCanceled() == true), then either return or throw an OperationCanceledException).

    The support library version of AsyncTaskLoader you are using though doesn't seem to fully implement cancellation at this time (not in mid-flight at least, and a cursory comparison of the framework and of the support version of Loader seems to suggest that cancellation might not be supported at all...).

    http://developer.android.com/reference/android/content/Loader.html http://developer.android.com/reference/android/support/v4/content/Loader.html

    Two ways to alleviate the problem come to my mind:

    • create two implementations of your Loader (one using the framework for API level 11 and above, and one without the cancel feature for older devices)
    • create an android.support.v4.content.Loader subclass and handle each AsyncTask and cancellation request yourself
    0 讨论(0)
  • 2021-01-03 17:15
    public boolean cancelLoad() {
        ...
        boolean cancelled = mTask.cancel(false);
    }
    
    
    
            @Override
            public Date loadInBackground() { // AsyncTaskLoader only
                Log.d(TAG, "Loader.loadInBackground()");
    
                try {
                    // there will be some HttpClient.execute()
                    while(true) {
                        Thread.sleep(100);
                        Log.d(TAG, "Loader.loadInBackground() still running");
    
                       if(cancelled)                 <---------
                          return new Date();         <----------
                    }
    
                } catch (InterruptedException e) {
                    Log.d(TAG, "Loader.loadInBackground() interupted");
                }
                Log.d(TAG, "Loader.loadInBackground() finished");
                return new Date();
            }
    
    0 讨论(0)
提交回复
热议问题