Android often has some operations such as network requests, file read/write, and database operations, which are time-consuming. We need to put them in a non-UI thread for processing. At this time, we need to handle the changes and interactions of the UI before and after the task. We need to use asynchronous request processing similar to js. Here we will summarize what I have learned to facilitate my memory and others' browsing.
AsyncTask
New aysnctask(cmd.exe cute ();
AsyncTask runs in the UI thread and a time-consuming task thread according to the process.
(1) onPreExecute () executes preprocessing. It runs in the UI thread and can be used to prepare background tasks, such as drawing a progress bar control.
(2) doInBackground (Params...) is implemented here. doInBackground (Params...) is the key to AsyncTask and must be reloaded. In this method, you can use publishProgress (Progress...) to change the current Progress value.
(3) onProgressUpdate (Progress...) runs on the UI thread. If publishProgress (Progress...) is used in doInBackground (Params...), this method is triggered. Here, you can make a specific response to the progress bar Control Based on the Progress value.
(4) onPostExecute (Result) runs on the UI thread and can process the results of background tasks. The Result is the return value of doInBackground (Params. This method should also be reloaded frequently. If the Result is null, the background task is not completed (canceled or abnormal ).
2. Handler
When creating a Handler, you must upload Lopper. The default value is the UI thread.
Send a Message to the main thread or Handler thread through Handler,
3. Activity. runOnUiThread (Runnable)
Runnable can be executed in the UI thread
4. View. post (Runnable)
Runnable runs in the UI thread
View. post (Runnable) method. In the post (Runnable action) method, View gets the Handler of the current thread (that is, the UI thread), and then post the action object to the Handler. In Handler, it packs the passed action object into a Message (the callback of the Message is action), and then inputs it into the Message loop of the UI thread. When Handler processes the Message again, a branch (uninterpreted) is set for it and the runnable run method is called directly. At this time, it has been routed to the UI thread, so we can update the UI without any concerns.
In essence, all asynchronous operations are implemented through Handler.
Basically, you can use similar task processing mechanisms in message loops.
The csdn blog editor is not easy to use and does not support markdown. This is from my blog. Welcome to my independent blog!
Original address: http://blog.isming.me/blog/2014/03/16/androidyi-bu-cao-zuo-zong-jie/, reproduced please indicate the source.