Android: asynchronous task Basics

Source: Internet
Author: User

Android: asynchronous task Basics

During the interview today, the interviewer talked to me about synchronization and Asynchronization, because when talking about synchronization, I thought about thread synchronization, and shared critical resources, deadlocks, and so I kept talking about this, asynchronous threads have never been heard. After reading the ball, I thought about it and checked it. I don't know if he was expecting me to answer the question of using Handler to refresh the main thread, I usually call this asynchronous task-when I was on the last day, the interviewer asked me how to refresh the UI thread, and then I used AsyncTask. Well, it doesn't matter, because I want to rewrite the previously written AsyncTask. It can also be regarded as an anxious wait time.

Asynchronous task-related

Android from 2.3 (or 3.0 ...?) At first, we cannot execute some time-consuming tasks in the main thread. Generally, we need an asynchronous task mechanism to solve the problem of refreshing the UI in the Child thread.

Several important classes on the API: (I should ask the interviewer if there are any classes to remind me)

Message:Defines a Message object that can carry some fields or object data. the officially recommended instantiation method is: Message. obtain () MessageQueue:Queue for storing messages Handler:When you create a new Handler, it is bound to the MessageQueue created by the current thread. There are two main roles: one is to queue messages and the other is to process messages. Looper:A class that runs the message queue of a thread. By default, the thread does not contain the message queue. prepare()And loop(). The main thread comes with message queue.

The process of stealing is as follows:

Three methods for implementing asynchronous tasks

Currently, I know three methods for implementing asynchronous tasks:

Use Handler + MessageTo use AsyncTaskClass call runOnUiThread()Method

The following describes how to use the three methods in the form of code Annotations:

Handler + Message
Public class MainActivity extends ActionBarActivity {private TextView textView; // The anonymous internal class instantiates a Handler object private Handler handler = new Handler () {// override the handleMessage method, the asynchronous Message mechanism is used to refresh the UI public void handleMessage (Message msg) {textView. setText ("you got" + msg. what + "through handler") ;}}; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); textView = (TextView) findViewById (R. id. textview); new TestThread (). start ();} private class TestThread extends Thread {private int I = 1; public void run () {while (true) {/* pay attention to this, we can use Message message = Message. obtain () gets the Message object, and then calls the sendMessage () method with Handler. For more details, refer to API */handler. sendEmptyMessage (I ++); if (I> 100) break; try {sleep (1000);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}}}
AsyncTask

Paste the code of the previous Article directly here, because the article should be deleted later.

Public class MainActivity extends ActionBarActivity {Private TextView textView; Private Button button; Private MyAsyncTask asyncTask; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); textView = (TextView) findViewById (R. id. textview); button = (Button) findViewById (R. id. button); asyncTask = new MyAsyncTask (); // Click the button to perform the asynchronous task button. setOnClickListener (new OnClickListener () {@ Override public void onClick (View arg0) {// TODO Auto-generated method stub asyncTask.exe cute ("Leelit "); // this parameter is an input parameter, which is often used for URL download and can be left blank. });}/* The wildcard class AsyncTask has three parameters: Params, input parameter; Progress, Progress; Result, and return Result. You can also use Void to indicate that this parameter is null. */Private class MyAsyncTask extends AsyncTask
  
   
{@ Override protected String doInBackground (String... string) {// TODO Auto-generated method stub String conutString = string [0]; // string variable parameter int z = 0; // 0.5 billion calculation, simulate a time-consuming task for (int I = 0; I <1000000; I ++) {for (int j = 0; j <500; j ++) {z ++ ;}} conutString + = "has executed ++ computation for" + z + "times"; Log. e ("ProcessInfo", "the task is done"); return conutString; // return the calculation result to onPostExecute ()} @ Override protected void onPostExecute (String result) {// TODO Auto-generated method stub super. onPostExecute (result); textView. setText (result); // refresh the UI }}}
  

To display the task progress, you can rewrite the following method:

// The Variable Parameter type is the second parameter of the generic type, because I do not need it here, so it is Void @ Overrideprotected void onProgressUpdate (Void... values) {// TODO Auto-generated method stub super. onProgressUpdate (values );}

AnddoInBackground()Method callpublishProgress()
 

RunOnUiThread ()

You can call this method directly in the Child thread to perform operations on the main thread, which is the simplest operation.

Public class MainActivity extends ActionBarActivity {private TextView textView; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); textView = (TextView) findViewById (R. id. textview); new Thread (new Runnable () {@ Override public void run () {// TODO Auto-generated method stub try {Thread. sleep (2000);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace ();} final String result = "After a long-time execution"; // you can call runOnUiThread (new Runnable () {public void run () directly in the subthread () {textView. setText (result );}});}}). start ();}}

Let's take a look at the source code of this simple method.

public final void runOnUiThread(Runnable action) {        if (Thread.currentThread() != mUiThread) {            mHandler.post(action);        } else {            action.run();        }    }

Yes, we can see that it is implemented by encapsulating Handler. In fact, AsyncTask is the same, but the mechanism of AsyncTask is a bit more complicated.

Summary: asynchronous tasks can be implemented by Handler and Its encapsulated classes or methods.

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.