Notes for using AsyncTask: Use of asynctask
AsyncTask is an asynchronous processing thread that comes with android.
It carries many parameters
Easy to use
But there are some precautions
1:
Official Website Description: AsyncTasks shocould ideally be used for short operations (a few seconds at the most .) if you need to keep threads running for long periods of time, it is highly recommended you use the varous APIs provided byjava.util.concurrent
Package suchExecutor
,ThreadPoolExecutor
AndFutureTask
.
That is to say, AsyncTask is only suitable for executing some short programs. If you want to use a long-term thread, you still need to use the following three classes for support.
2:
onPreExecute()
,
doInBackground(Params...)
,
onProgressUpdate(Progress...)
,
onPostExecute(Result)
,
Let's look at these methods.
The other three methods are called by the main thread. You can print the thread ID and find that they are the same as the main thread ID.
None of the four methods can be called proactively without error.
3:
A new AsyncTask, which execute once in a while. If it is restarted, an error is reported. Only one new
4:
After cancel is used, the doInBackgroud method is still executed. This is why the official website recommends not to run for too long.
But how can we cancel doInBackgroup?
You just need to judge the isCancelled (sentence) in it, change the cycle condition to judge isCancelled (), and then you can stop the doInBackgroup.
So what method does the cancel () method mainly cancel?
Mainly later
onProgressUpdate(Progress...)
,
onPostExecute(Result)
Neither of the two methods will be executed, that is, the UI thread will not be updated.
This article is organized and published by www.zaojuzi.com.