First:
To learn how to use a knowledge point, you can take four steps:
First, what refers to the concept of AsyncTask. When downloading resources from the server and parsing json files, you must abide by the single-thread model principles when developing Android applications: android UI operations are not thread-safe and must be executed in the UI thread. In a single-threaded model, you must always remember the following two rules:
1. Do not block the UI thread
2. Make sure to only access the Android UI toolkit in the UI thread
When a program is started for the first time, Android starts a corresponding Main Thread at the same time. The Main Thread is mainly responsible for processing UI-related events, such as user key events, the user contacts screen events and Screen Drawing events, and distributes related events to corresponding components for processing. Therefore, the main thread is often called the UI thread.
Android provides several methods to access the UI thread in other threads.
Activity. runOnUiThread (Runnable)
View. post (Runnable)
View. postDelayed (Runnable, long)
AsyncTask is an abstract class. AsyncTask defines three generic types: Params, SS, and Result.
Input parameters for Params startup task execution, such as the URL of the HTTP request.
Percentage of Progress background tasks.
Result: The Result returned when the task is executed in the background, such as String.
The execution of AsyncTask is divided into four steps. Each step corresponds to a callback method, which should not be called by the application. All developers need to do is implement these methods.
1) subclass AsyncTask
2) implement one or more of the following methods defined in AsyncTask
OnPreExecute (), this method will be called by the UI thread before the actual background operation is executed. You can make some preparations in this method, such as displaying a progress bar on the interface.
DoInParams...) will be executed immediately after the onPreExecute method is executed. This method runs in the background thread. Here, we will primarily perform those time-consuming background computing tasks. You can call publishProgress to update the real-time task progress. This method is an abstract method and must be implemented by sub-classes.
OnProgressUpdate (Progress...), after the publishProgress method is called, UI thread will call this method to display the Progress of the task on the interface, for example, display through a Progress bar.
OnPostExecute (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.
To correctly use the AsyncTask class, the following guidelines must be followed:
1) The Task instance must be created in the UI thread.
2) The execute method must be called in the UI thread.
3) The task can only be executed once. Otherwise, exceptions may occur during multiple calls.
The doInBackground method and the onPostExecute parameter must correspond to each other. These two parameters are specified in the generic parameter list declared by AsyncTask. The first parameter is the parameter accepted by doInBackground, and the second parameter is the parameter indicating the progress, the third parameter is the doInBackground return and the parameter passed in onPostExecute.
Second, how to use it, for example, update the progress bar through Asynctask
Package com. example. ex24_asynctask;
Import android. R. integer;
Import android. OS. AsyncTask;
Import android. OS. Bundle;
Import android. app. Activity;
Import android. util. Log;
Import android. view. Menu;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
Import android. widget. SeekBar;
Public class MainActivity extends Activity {
Private SeekBar;
Class MyAsyncTask extends AsyncTask <String, Integer, String> {
@ Override
Protected void onProgressUpdate (Integer... values ){
// Update the progress bar
Bar. setProgress (values [0]);
};
Protected void onPostExecute (String result ){
}
@ Override
Protected String doInString... params ){
// TODO Auto-generated method stub
Log. e ("mainActivity", "doInBackground" + params );
For (int I = 0; I <10; I ++ ){
Try {
Thread. sleep (500 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
PublishProgress (I + 1 );
}
Return null;
};
}
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
// Obtain the button id
Button btn = (Button) findViewById (R. id. button1 );
Bar = (SeekBar) findViewById (R. id. seekBar1 );
Bar. setMax (10 );
OnClickListener listener = new OnClickListener (){
@ Override
Public void onClick (View v ){
Download ();
}
};
Btn. setOnClickListener (listener );
}
Protected void download (){
// Create an object
MyAsyncTask asyncTask = new MyAsyncTask ();
AsyncTask.exe cute ("http://ww.baidu.com ");
}
@ Override
Public boolean onCreateOptionsMenu (Menu menu ){
// Inflate the menu; this adds items to the action bar if it is present.
GetMenuInflater (). inflate (R. menu. activity_main, menu );
Return true;
}
} |
Third: why is why used? Android's use of AsyncTask has the following benefits:
1. The thread overhead is high. If each task needs to create a thread, the application efficiency will be much lower;
2. threads cannot be managed. Anonymous threads are not controlled by the program after they are created and started. If many requests are sent, many threads will be started and the system will be overwhelmed;
3. In addition, handler must be introduced to update the UI in the new thread, which makes the Code look very bloated;
Fourth: where is used? It is generally used to obtain data from the server, load ListView data, images, etc.