AnsyncTask asynchronous task
Introduction to this section:
What this section brings to you is a lightweight class provided by Android for processing asynchronous tasks: AsyncTask, we usually Inherit AsyncTask, then implement asynchronous operations in the class, and then feed back the progress of asynchronous execution to the UI main thread~ Okay, maybe you don’t understand some concepts, and I think it’s still necessary to explain the concept of multi-threading, so let’s explain some conceptual things first!
1. Related concepts
1) What is multi-threading:
Answer: You must first understand these names: application, process, Threads, multi-threads! !
- Application (Application): A set of instructions (a set of static codes) written in a certain language to complete a specific task
- Process:A running program, an independent unit of system scheduling and resource allocation, the operating system will allocate it to each process A section of memory space, the program is dynamically executed sequentially, the manager code is loaded -> executed -> The complete process of execution is completed!
- Thread (Thread): An execution unit smaller than a process. Each process may have multiple threads. Threads need to be placed in one process to execute! Threads are managed by the program! ! ! The process is scheduled by the system! ! !
- Multithreading concept(Multithreading): Execute multiple instructions in parallel, and allocate the time slice of the CPU to each thread according to the scheduling algorithm, which is actuallyTime-sharing execution, but the switching time is very short, and the user feels it is at the same time!
A simple example: You hang up QQ and suddenly want to listen to music. Do you need to turn off QQ and then start XX player? ? The answer is no, let’s open the player directly Just play songs, QQ is still running, right? This is simple multi-threading~ In actual development, there are also such examples, such as the application is running, We have found a new version and want to update it in the background. At this time, we usually open up a background thread to download the new version of apk, but at this time We can also use other features in the app! This is an example of using multi-threading~
2) The concept of synchronization and asynchronousness:
Answer: Synchronization: When we execute a certain function, the call cannot return before we get the result! To put it simply, it means that it must be Wait for the previous thing to be completed before you can do the next thing; to give a simple example: if you have sex, in order to avoid killing someone, you must put on a condom first. Then have sex again, right? Put on the condom -> Then have sex. For example, if you don’t have a condom, then the sex operation will have to wait until you put on the condom. After you buy the condom and bring it with you, you can start having sex at this time~A vivid example, ♪(^∇^*)Asynchronous: It is relative to synchronization. When we execute a certain function , we don’t need to get the result immediately, we can normally To do other operations, this function can notify us or call back after completion; or the background download example above, background download, After we execute the download function, we don’t need to care about its download process. We can just notify us when the download is completed~
3) Why should Android introduce asynchronous tasks
Answer: Because when the Android program is first started, a corresponding main thread (Main Thread) will be started at the same time. This main thread is mainly responsible for processing UI related events! Sometimes we also call it the UI thread! In Android App, we must abide by the rules of this single-threaded model: Android UI operations are not thread-safe and these operations need to be executed in the UI thread! If we are in a non-UI thread, such as new Thread() in the main thread, create another thread, and then directly modify the value of the UI control in it; At this time, the following exception will be thrown: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its viewsIn addition, there is another point, if we take all the time-consuming operations If placed in the UI thread, if the UI thread does not respond to the request for more than 5s, then At this time, an ANR (Application Not Responding) exception will be triggered, which means that the application is not responding~ The last thing is: after Android 4.0, it is forbidden to perform network operations in the UI thread~ Otherwise, it will report: android.os.NetworkOnMainThreadException
The above reasons all explain Android The significance of introducing asynchronous tasks, of course, is not necessary to implement asynchronous tasks without our explanation in this section. AsyncTask, we can open a thread ourselves. After completing the relevant operations, we can update the UI through the following two methods:
- The Handler we learned earlier, we write the UI update in the Handler, and then notify the UI through methods such as sendMessage() Update, don’t forget the difference between Handler written in the main thread and sub-thread~
- Use Activity.runOnUiThread(Runnable) to create the code for updating ui in Runnable. When updating UI, put Runnable Just pass the object in~
2. Full analysis of AsyncTask:
1) Why use AsyncTask?
Answer: We can use the above two methods to complete our asynchronous operations. Adding asynchronous operations requires us to write more or is more cumbersome. Should we new Thread() and then use the above method to notify the UI of updates? Programmers tend to be lazy. Since the official We provide AsyncTask, an encapsulated lightweight asynchronous class, why not use it? We can do it with dozens of lines of code Our asynchronous operation, and the progress is controllable; compared to Handler, AsyncTask is simpler and faster ~ Of course, this is only suitable for Simple asynchronous operations. In addition, the most commonly used asynchronous operations are network operations, image loading, data transmission, etc. AsyncTask It can meet the needs of beginners for the time being. Thank you for the small application. But after the company actually does projects, we will use third-party ones more. There are many frameworks, such as Volley, OkHttp, android-async-http, XUtils, etc. We will choose 1-2 frameworks for the advanced tutorials later. Learning, of course you can find materials to learn by yourself, but it is still necessary to master AsyncTask!
2) The basic structure of AsyncTask
AsyncTask is an abstract class. Generally, we will define a class to inherit AsyncTask and then override related methods~ Official API: AsyncTask
- Parameters to build AsyncTask subclass:
- ##Related methods and execution processes:
3. AsyncTask usage example:##Notes :
Because we haven’t learned Android yet As for the network, I'll take care of all the beginners here, and use delay here. Threads to simulate the process of file downloading~ I will write a few examples for you when talking about the network later~
Implementation renderings:
Layout file: activity.xml
Define a delay operation, used to simulate downloads: Customized AsyncTask: MainActivity.java: 好的,本节一开始给大家普及了下应用程序,进程,线程,多线程,异步,同步的概念;接着又讲解
了下Android中为何要引入异步操作,然后介绍了下AsyncTask的用法,当然上面也说了,异步操作在网络
操作用的较多,后面在讲解网络操作时会用到这个AsyncTask,敬请期待~本节就到这里,谢谢~
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MyActivity">
<TextView
android:id="@+id/txttitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!--设置一个进度条,并且设置为水平方向-->
<ProgressBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/pgbar"
style="?android:attr/progressBarStyleHorizontal"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnupdate"
android:text="更新progressBar"/>
</LinearLayout>
//Delay operation, used to simulate downloads
public void delay()
{
try{
Thread.sleep(1000);
}
}
{
private TextView txt;
private ProgressBar pgbar;
public MyAsyncTask(TextView txt,Pro gressBar pgbar )
In the UI thread, it is mainly used for asynchronous operations, by calling the publishProgress() method
//Trigger onProgressUpdate to operate the UI
@Override
protected String doInBackground(Integer... params) {
DelayOperator dop = new DelayOperator();
int i = 0;
for (i = 10;i <= 100;i+=10)
dop.delay();
publishProgress(i);
. Control settings
@Override
protected void onPreExecute() {
txt.setText("Start executing asynchronous thread~");
}
//In doBackground In the method, this method will be triggered every time the publishProgress method is called
//Running in the UI thread, you can operate the UI controls
@Override
protected void onProgressUpdate(Integer.. . values) {
int value = values[0];
pgbar.setProgress(value);
}
}
private TextView txttitle;
private ProgressBar pgbar;
private Button btnupdate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txttitle = (TextView)findViewById(R.id.txttitle);
pgbar = (ProgressBar)findViewById(R.id.pgbar);
btnupdate = (Button)findViewById(R.id.btnupdate);
btnupdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyAsyncTask myTask = new MyAsyncTask(txttitle,pgbar);
myTask.execute(1000);
}
});
}
}本节小结: