In the previous article, we used Thread + Handler to update the UI. Android provides a relatively lightweight AsyncTask, which is mainly used for some simple logic operations to update the UI.
Public class ProAT extends AsyncTask <String, Integer, String> {
/*
* The first parameter is the parameter passed in by doInBackground,
* The second parameter is the onProgressUpdate parameter, which is passed by publishProgress (Interger) called in doInBackground;
* The third parameter is the doInBackground return value and the parameter passed in onPostExecute.
*/
@ Override
Protected void onPreExecute (){
// This method will be called by the UI thread before the actual background operation is executed. You can make some preparation work in this method, such as the prompt to turn chrysanthemum on the Interface
System. out. println ("onPreExecute ---> Task start ");
Super. onPreExecute ();
}
@ Override
Protected String doInBackground (String... params ){
// It will be executed immediately after the onPreExecute method is executed. This method runs in the background thread.
// It is mainly responsible for performing time-consuming background computing.
System. out. println ("doInBackground ----> ");
Try {
Thread. sleep (5000 );
// You can call publishProgress to update the real-time task progress. This method is an abstract method and must be implemented by sub-classes.
PublishProgress (1 );
} Catch (InterruptedException e ){
// TODO: handle exception
E. printStackTrace ();
}
Return "doInBackground ";
}
@ Override
Protected void onProgressUpdate (Integer... values ){
System. out. println ("Update Progress" + values [0]);
// After the publishProgress method is called, the UI thread will call this method to display the progress of the task on the interface, for example, through a progress bar.
Super. onProgressUpdate (values );
}
@ Override
Protected void onPostExecute (String result ){
// After doInBackground is executed, the onPostExecute method will be called by the UI thread, and the background computing result will be passed to the UI thread through this method
// Used to update the UI
System. out. println ("onPostExecute ----->" + result );
Super. onPostExecute (result );
}
@ Override
Protected void onCancelled (){
// When the user cancels the operation.
Super. onCancelled ();
}
}
Main thread call
Public class AsyncTaskActivity extends Activity {
/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
ProAT pro = new ProAT ();
// Execute must be called in the main thread
Pro.exe cute ("url ");
}
}
Author "Ah Di"