Cancel AsyncTask after some time

后端 未结 5 468
别那么骄傲
别那么骄傲 2020-12-31 06:11

This could be a duplicate question but I did not find what I was looking for. I am calling an AsyncTask in the UI activity new LoadData().execute(); and in doI

5条回答
  •  臣服心动
    2020-12-31 06:39

    Short answer is you CAN'T cancel an AsyncTask once its started. What you can do, is insert a loop inside doInBackGround() which will check for isCancelled() and if it is set to true sometime in the future - return a value from the function (which will in turn call onPostExecute() if you have defined it);

    Note that just because you can't stop an AsyncTask doesn't mean that the OS won't cancel it if it's low on memory. You should have this in mind if you are doing essential tasks in the AsyncTask (ones that you want executed 100%). If so, it is better to use a Service - a component that is automatically killed and restarted by the OS as need.

提交回复
热议问题