Android Basics Beginner Tutorial--3.7 ansynctask Async Task

Source: Internet
Author: User

Android Basics Beginner Tutorial--3.7 ansynctask Async Task

tags (space delimited): Android Basics Beginner Tutorial

Introduction to this section:

What this section brings to you is a lightweight class for handling asynchronous tasks that Android provides us: Asynctask. We are usually
Inherit the Asynctask, and then implement the asynchronous operation in the class, and then run the progress asynchronously. Feedback to the UI main thread ~
Well, there may be some concepts you do not understand, it is necessary to explain the concept of multi-threaded, then the first explanation of some conceptual things!

1. Related concepts 1) what is Multithreading:

A: First you need to know these names: applications, processes, threads. Multithreading!

  • Application (Application): A set of instructions (a set of static code) written in a language in order to complete a specific task
  • process : a running program . A separate unit for system scheduling and resource allocation. The operating system assigns each process
    A memory space, the program is running dynamically. Run the complete process, run, manager code onboarding!

  • thread: a smaller running unit than a process, each process may have multiple threads, and threads need to be able to run in a single process!
    Threads are managed by the program!

    。 And the process is scheduled by the system!!!

  • Multithreading Concept (Multithreading): Running multiple instructions in parallel, the CPU time slices in accordance with the scheduling algorithm. Assigned to individual threads, which are actually tick-run . It's just that the switching time is very short. The user feels the same time!

to give a simple example:
You hang QQ, suddenly want to listen to songs, you need to turn off QQ, and then to start XX player? The answer is no, we open the player directly
Singing is good, QQ is still running, right! This is the simple multithreading ~ in the actual development, there are also examples, for example, the application is running,
A new version number was found. Want to update the background, this time generally we will open up a background thread, to download the new version number of the APK, but this time
We are also able to use other features in the app. This is the use of multithreading sample ~

2) The concept of synchronous and asynchronous:

A: sync : When we run a feature, before we get the results. This call cannot be returned. The simple point is that you must
Do the next thing before you finish it. Take a simple example: for example, you have to wear a condom in order to avoid human life.
and then snap it ~ ~ and then snapped, for example, you have no condom. That snapped operation was going to wait. Until you put
Condoms bought back with, this time can start to pop ~ an image of the sample. (^?^*)
Async : And synchronization are relative. When we run a function, we don't need to get the results right away, we can properly
To do other things, this function can be notified after the completion of the notification or callback to tell us. or the above background download example, background download,
After we run the download feature, we don't have to care about its download process. When the download is complete, notify us to be able to ~

3) Android is very well to introduce asynchronous tasks

A: Since the Android program was just started. will start a corresponding main thread at the same time, the main thread is responsible for handling
UI-related events! Sometimes we also call him the UI thread! In the Android app, we have to follow the rules of this single-threaded model:
Android UI operations are not thread-safe and these operations need to be run in the UI thread!


If we were in a non-UI thread, for example, in the main thread, the new thread () would open up a different threading, and then change the UI control's value directly inside.
This throws the following exception:
android.view.viewroot$calledfromwrongthreadexception:only The original thread that created a view hierarchy can Touc H its Views
Other than that. Another point. Suppose we put a time-consuming operation in the UI thread, assuming that the UI thread exceeds 5s without responding to the request. So
This time will cause the ANR (application not responding) exception, that is, the application is unresponsive ~
Last but not least: after Android 4.0, it is forbidden to run network operations in the UI thread ~ Otherwise it will be reported:
android.os.NetworkOnMainThreadException

All of these reasons illustrate the meaning of Android's introduction of asynchronous tasks, and of course, it is not possible to implement Asynchrony in this section of our commentary
The Asynctask. We are able to open up a thread ourselves, after the relevant operation. The UI update is done in two ways:

  1. The handler we learned before. We wrote the UI update in handler. The UI is then notified via methods such as SendMessage ()
    Update, and don't forget to handler the difference between the main thread and the child thread Oh ~
  2. Use Activity.runonuithread (Runnable) to create the code that updates the UI in Runnable, and when the UI is updated, Runnable
    The object can be passed in.
2.AsyncTask full resolution: 1) Why use Asynctask?

A: We can use the above two methods to complete our asynchronous operation, to increase the number of asynchronous operations we write more, or more cumbersome,
Are we new Thread () and then notify the UI update using the above method? Program apes are more like lazy, since the official gave me
Asynctask is a lightweight asynchronous class that is packaged in this package. Why not? We'll be done with dozens of lines of code.
Our asynchronous operation, and the progress is controllable. Compared to the handler,asynctask appears more simple, fast ~ Of course, this is only suitable for
Simple asynchronous operation, in addition. The most practical asynchronous use is the network operation. Image loading, transmission of data, etc. Asynctask
Temporary to meet the needs of people who have just started learning, thank you small application. But after the company actually did the project. We have a lot of other uses of the third hair
Frameworks, such as volley,okhttp,android-async-http,xutils and so on, the next advanced tutorial we will choose 1-2 frames for
Learning, of course, you can find information on their own learning, but the mastery of asynctask is still very necessary.

2) Basic structure of Asynctask:

Asynctask is an abstract class, generally we will define a class to inherit asynctask and then rewrite the relevant method ~
Official Api:asynctask

  • To construct the Asynctask sub-class:

  • Related methods and operating procedures:

  • Precautions:

3.AsyncTask using Demo sample:

Since we haven't learned the Android web, take care of the people who are just beginning to learn. Here with the delay
Thread to simulate the process of file download ~ Later on the network there will be a few examples to write to you ~

Realize:

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  =;       <TextViewandroid:id= "@+id/txttitle"android:layout_width="Wrap_ Content "android:layout_height=" wrap_content " />                                    <!--set a progress bar and set it to horizontal--      <progressbar  android: Layout_width  = "fill_parent"  android:layout_ Height  = "wrap_content"  android:id  =< Span class= "Hljs-value" > "@+id/pgbar"  style  = " ? android:attr/progressbarstylehorizontal "/>       <buttonandroid:layout_width="Wrap_content"android:layout_height= "Wrap_content" android:id="@+id/btnupdate"android:text="Update ProgressBar"/>                                          </linearlayout>  

Defines a delay operation. For simulation Downloads:

publicclass DelayOperator {      //延时操作,用来模拟下载      publicvoiddelay()      {          try {              Thread.sleep(1000);          }catch (InterruptedException e){              e.printStackTrace();;          }      }  }  

Define yourself Asynctask

 Public classMyasynctask extends Asynctask<integer,integer,string> {PrivateTextView txt;PrivateProgressBar Pgbar; Public Myasynctask(TextView Txt,progressbar Pgbar) {super (); This. txt = txt; This. Pgbar = Pgbar; }//The method does not run in the UI thread, primarily for asynchronous operations, by calling the Publishprogress () method    //Trigger Onprogressupdate to manipulate the UI@OverrideprotectedStringDoinbackground(Integer ...params) {Delayoperator DOP =NewDelayoperator ();inti =0; for(i =Ten; I <= -; i+=Ten) {Dop.delay ();          Publishprogress (i); }returni +params[0].intvalue () +""; }//This method runs in the UI thread and can be set on the UI control@Overrideprotected void OnPreExecute() {Txt.settext ("Start running async threads ~"); }//In the Dobackground method, the method is triggered every time the Publishprogress method is called    //Run in UI thread, can operate on UI control@Overrideprotected void onprogressupdate(Integer ... values) {int value= values[0]; Pgbar.setprogress (value); }  }

Mainactivity.java:

 Public  class myactivity extends actionbaractivity {      PrivateTextView Txttitle;PrivateProgressBar Pgbar;PrivateButton 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 (NewView.onclicklistener () {@Override               Public void OnClick(View v) {Myasynctask MyTask =NewMyasynctask (Txttitle,pgbar); Mytask.execute ( +);      }          }); }  }
This section summarizes:

Well, this section starts with the app. Process. threads, multi-threaded, asynchronous. The concept of synchronization;
The reason why the introduction of asynchronous operations in Android, and then introduced the use of the next asynctask, of course, above also said. Asynchronous operations in the network
Operation with more, behind in the commentary network operation will use this asynctask, please look forward to this section on here, thank you ~

Android Basics Beginner Tutorial--3.7 ansynctask Async Task

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.