Asynctask has three attribute values and four steps

Recently, I learned to use asynctask to handle network operations. Although the code doesn't look very complex, there are still many doubts. So I read the API documentation and showed the code I learned and practiced here. If there is any error, please point it out!

1、 < params, progress, result > about asynctask

When creating a subclass of asynctask, you must give these three specific type values. Angle brackets mean generic. I don't quite understand the API documentation, but look down

doInBackground(Params...)

publishProgress(Progress...)

onProgressUpdate(Progress...)

onPostExecute(Result)

You can know who they are passed to, and the parameters with... In parentheses can be understood as arrays.

2、 Four steps of asynctask

1. Onpreexecute(): this method is performed before the task starts. It is called by the UI thread (main thread), that is, UI operations can be performed. At the end, I will give the log printing information.

2. Doinbackground (params...): this method is performed in the background immediately after onpreexecute() is completed to execute the task and pass the result to onpostexecute (result). In addition, during this period, you can call publishprogress (Progress...), which can pass some data to onprogressupdate (Progress...).

3. Onprogressupdate (Progress...): this method will be called by the UI thread after publishprogress (Progress...) is called. Therefore, using publishprogress (Progress...) and onprogressupdate (Progress...) can make the UI effect of waiting or buffering when loading or reading network data. The renderings I gave at the end have similar functions.

4. Onpost execute (result): after doinbackground (params...) is completed, it is called by the UI thread to process the result here.

3、 The code I wrote when I practiced

This is the start task. Execute () here can pass in multiple parameters, such as execute (url1, URL2, url3)

Then, multiple tasks can be processed in doinbackground, and publishprogress and onprogressupdate are similar

4、 Final effect drawing

Before confirmation, the textview is empty. After confirmation and before the obtained information is loaded, the textview displays loading. It may GIF not be done well and looks strange. In addition, under normal circumstances, loading is a flash. Here is a screenshot of breakpoint debugging.

Finally, the log information of the four methods described above

The above is the whole content of this article. I hope the content of this article can bring some help to your study or work. At the same time, I also hope to support a lot of programming tips!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>