Cannot cancel running AsyncTask in AsyncTaskLoader

前端 未结 2 1262
天命终不由人
天命终不由人 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

提交回复
热议问题