Android basic getting started tutorial-3.7 AnsyncTask asynchronous task, androidansynctask

Source: Internet
Author: User

Android basic getting started tutorial-3.7 AnsyncTask asynchronous task, androidansynctask
Android basic tutorial-3.7 AnsyncTask asynchronous task

Tags (separated by spaces): basic Android tutorial

This section introduces:

This section introduces a lightweight class provided by Android for processing asynchronous tasks: AsyncTask.
Inherit AsyncTask, implement asynchronous operations in the class, and then feed back the asynchronous execution progress to the main UI thread ~
Well, you may not understand some concepts. I think it is necessary to explain the concept of multithreading. Let's explain some conceptual things first!

1. Related Concepts 1) What is multithreading:

A: First, you need to know these names: application, process, thread, and multithreading !!

  • Application): A set of commands (static code) written in a certain language to complete a specific task)
  • Process):Running ProgramSystem scheduling and resource allocationIndependent Unit, The operating system will assign each process
    A piece of memory space, the program is dynamically executed in turn, the Manager Code is loaded-> execution-> the complete execution process!
  • Thread): A smaller execution unit than a process. Each process may have multiple threads,The thread must be placed in a process before execution!
    The thread is managed by the program !!! The process is scheduled by the system !!!
  • Multithreading): Execute multiple commands in parallelTime sliceAccording to the scheduling algorithm, the allocation to each thread is actuallyTime-sharing executionBut the switching time is very short, and the user feels it is the same!

A simple example:
When you are playing QQ, you suddenly want to listen to songs. Do you need to turn off QQ and then start XX player? The answer is no. Open the player directly.
Just play the song, QQ is still running, right! This is simple multithreading ~ In actual development, there are also such examples, such as the application is running,
If you want to update the new version in the background, we usually open up a background thread to download the new version of apk.
We can also use other features in the application! This is an example of multithreading ~

2) concepts of synchronization and Asynchronization:

A:Synchronization: When we execute a function, this call cannot be returned before the result is obtained! Simply put, it must
You can do the next thing only after the previous thing is done. For example, you must first wear a condom to avoid making a fortune,
And then click it, right ~ Then, if you don't have a set, you have to wait until you
Buy a condom and bring it back. At this time, you can get started ~ An image example,♪(^ *)
Asynchronous: It is opposite to synchronization. When we execute a function, we do not need to get the result immediately. We can normally
For other operations, this function can be notified or called back to tell us after completion; or the example of background download above, background download,
After the download function is executed, we do not need to care about its download process. After the download is complete, we will be notified ~

3) Why does Android introduce asynchronous tasks?

A: When the Android program is started, a corresponding Main Thread is started at the same time. This Main Thread is mainly responsible for processing
UI-related events! Sometimes we call it a UI thread! In Android apps, we must follow the rules of this single-thread model:
Android UI operations are not thread-safe and must be executed in the UI thread!
Assume that we open another Thread in a non-UI Thread, for example, new Thread () in the main Thread, and then directly modify the value of the UI control in it;
The following exception is thrown:
Android. view. ViewRoot $ CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views
In addition, if we put all the time-consuming operations in the UI thread, if the UI thread has not responded to the request for more than 5s, then
At this time, the ANR (Application Not Responding) exception will be thrown, that is, the Application has no response ~
The last point is: after Android 4.0, network operations are prohibited in the UI thread ~ Otherwise, the following message will be reported:
Android. OS. NetworkOnMainThreadException

The above reasons all illustrate the significance of introducing asynchronous tasks to Android. Of course, asynchronous implementation is not required in this section.
In AsyncTask, we can open up a thread by ourselves. After completing the relevant operations, we can update the UI using the following two methods:

2. Full AsyncTask resolution: 1) Why is AsyncTask used?

A: We can use the above two methods to complete our asynchronous operations. There are many or cumbersome asynchronous operations that require us to write,
Do we use the new Thread () method to notify UI updates? Programmers prefer to be lazy.
We provide AsyncTask, a lightweight asynchronous class encapsulated. Why not? We can use dozens of lines of code to complete
Our asynchronous operations, and the progress is controllable; compared with Handler, AsyncTask is simpler and faster ~ Of course, this is only suitable
Simple asynchronous operations. In addition, the most used asynchronous operations are network operations, image loading, data transmission, and AsyncTask.
For the time being, it can satisfy the needs of beginners. Thank you for your small application. But after the company is working on a project, we will use the third release.
There are many frameworks, such as Volley, OkHttp, android-async-http, and XUtils. We will select one or two frameworks for the next advanced tutorial.
Learning, of course, you can find your own materials to learn, but it is necessary to master AsyncTask!

2) Basic Structure of AsyncTask:

AsyncTask is an abstract class. Generally, we define a class to inherit AsyncTask and then rewrite the related methods ~
Official API: AsyncTask

  • Parameters for constructing AsyncTask subclass:

  • Related methods and procedures:

  • Note:

3. Example of AsyncTask:

Because we haven't learned about the Android network yet. Here we will take care of all the beginners. Here we will use latency.
Thread to simulate the file download process ~ I will give you some examples on networks later ~

Implementation:

Layout file: activity. xml:

<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" 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 "/> <! -- Set a progress bar and set it to the horizontal direction --> <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 = "Update progressBar"/> </LinearLayout>

Define a delayed operation for simulating download:

Public class DelayOperator {// delayed operation, used to simulate downloading public void delay () {try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();;}}}

Custom AsyncTask

Public class MyAsyncTask extends AsyncTask <Integer, Integer, String> {private TextView txt; private ProgressBar pgbar; public MyAsyncTask (TextView txt, ProgressBar pgbar) {super (); this.txt = txt; this. pgbar = pgbar;} // This method is not running in the UI thread and is mainly used for asynchronous operations. By calling 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);} return I + params [0]. intValue () + "";} // This method runs in the UI thread. You can set the UI control @ Override protected void onPreExecute () {txt. setText ("start executing asynchronous thread ~ ");} // In the doBackground method, the publishProgress method is triggered every time it is called. // The method runs in the UI thread, you can operate on the UI control @ Override protected void onProgressUpdate (Integer... values) {int value = values [0]; pgbar. setProgress (value );}}

MainActivity. java:

public class MyActivity extends ActionBarActivity {      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);              }          });      }  }  
Summary:

Okay. At the beginning, this Section introduced the concepts of applications, processes, threads, multithreading, Asynchronization, and synchronization.
Why should I introduce asynchronous operations in Android and then introduce the usage of AsyncTask? Of course, as mentioned above, asynchronous operations are performed on the network
This AsyncTask will be used in subsequent network operations ~ This section is here. Thank you ~

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.