Cannot cancel running AsyncTask in AsyncTaskLoader

前端 未结 2 1277
天命终不由人
天命终不由人 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: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();
            }
    

提交回复
热议问题