Multi-thread processing and Handler explanation for Android Development

Source: Internet
Author: User

Multi-thread processing and Handler explanation for Android Development

 

Why multithreading is required during Android development?

The Service, Activity, and Broadcast we created are all handled by a main thread. Here we can understand it as a UI thread. However, it takes a long time to perform some time-consuming operations, such as reading and writing large files, database operations, and network downloads. In order not to block the user interface, the ANR response Prompt window appears, at this time, we can consider using the Thread to solve the problem.

What problems will the Thread encounter in Android?

For programmers who have been engaged in the development of J2EE, Thread is relatively simple. They can directly create and rewrite the run method anonymously and call the start method for execution. It can be inherited from the Runnable interface, but for the Android platform, the UI control is not designed as a thread security type. Therefore, some synchronization mechanisms need to be introduced to refresh it, in this case, Google designed Android by referring to the Win32 message processing mechanism.

PostInvalidate () method

You can use the postInvalidate () method in the thread to refresh a View as the base class interface, and provide some rewriting methods such as postInvalidate (int left, int top, int right, int bottom) to refresh a rectangular area and perform delayed operations, such as postInvalidateDelayed (long delayMilliseconds) or postInvalidateDelayed (long delayMilliseconds, int left, int top, int right, int bottom) method. The first parameter is millisecond, as shown below:

Void
PostInvalidate ()
 
Void
PostInvalidate (int left, int top, int right, int bottom)
 
Void
PostInvalidateDelayed (long delayMilliseconds)
 
Void
PostInvalidateDelayed (long delayMilliseconds, int left, int top, int right, int bottom)
 

Handler

Of course, the recommended method is to use a Handler to handle this. You can call the postMessage or sendMessage method of the handler object in the run method of a thread. The Android Program maintains a message queue, this will be handled in turn. If you are a Win32 programmer, you can understand the message processing well. However, compared with Android, PreTranslateMessage does not provide internal interference methods.

The handler is responsible for encapsulating the information to be transmitted into a Message, which is implemented by calling the obtainMessage () of the handler object. Send the message to logoff, which is implemented by sendMessage () of the handler object. Then, logoff puts the Message into MessageQueue. When the logoff object sees that MessageQueue contains a Message, it is broadcasted. After the handler object receives the message, it calls the handleMessage () method of the corresponding handler object to process it.

 

Handler mainly accepts the data sent by the sub-thread and uses the data to update the UI with the main thread.
When an application is started, Android starts a main thread (that is, the UI thread). The main thread is the UI control in the management interface for event distribution. For example, if you click a Button, Android will distribute the event to the Button to respond to your operation. If you need a time-consuming operation, such as reading data online or reading a large local file, you cannot put these operations in the main thread ,, if you put it in the main thread, the interface will be suspended. If it has not been completed in five seconds, you will receive an error message "Force disable" from the Android system ". at this time, we need to put these time-consuming operations in a sub-thread. Because the sub-thread involves UI update, the main Android thread is thread insecure, that is, updating the UI can only be updated in the main thread. Operations in the Child thread are dangerous. at this time, Handler emerged to solve this complicated problem. Because Handler runs in the main thread (in the UI thread), it and the sub-thread can transmit data through the Message object, at this time, Handler is responsible for receiving the Message object (containing data) transmitted by the subthread using the sedMessage () method ), put these messages into the main thread queue and update the UI with the main thread.


Handler has some features: handler can distribute Message objects and Runnable objects to the main thread, and each Handler instance will be bound to the thread that creates the Handler (usually located in the main thread ),
It has two functions: (1) arrange the message or Runnable to execute somewhere in a main thread


(2) Schedule an action to be executed in different threads
Methods for sending messages in Handler
Post (Runnable)
PostAtTime (Runnable, long)
PostDelayed (Runnable long)
SendEmptyMessage (int)
SendMessage (Message)
SendMessageAtTime (Message, long)
SendMessageDelayed (Message, long)
The post method above allows you to arrange a Runnable object to the main thread queue. The sendMessage class method allows you to arrange a Message object with data to the queue and wait for updates.

Handler instance
// The subclass must inherit the Hendler class and override the handleMessage (Message msg) method to accept thread data.
// The following is an instance. Its function is to modify the content of the interface Button through a thread.

Public class MyHandlerActivity extends Activity {

Button button;

MyHandler myHandler;

Protected void onCreate (Bundle savedInstanceState ){

Super. onCreate (savedInstanceState );

SetContentview (R. layout. handlertest );

Button = (Button) findViewById (R. id. button );

MyHandler = new MyHandler ();

// When a new Handler instance is created, it is bound to the queue of the current thread and message to start distributing data.

// Handler has two functions: (1) scheduled Message execution and Runnalbe object execution

// (2): let an action be executed in different threads.

// It schedules messages, using the following method

// Post (Runnable)

// PostAtTime (Runnable, long)

// PostDelayed (Runnable, long)

// SendEmptyMessage (int)

// SendMessage (Message );

// SendMessageAtTime (Message, long)

// SendMessageDelayed (Message, long)

// The above method starts with post and allows you to process Runnable objects

// SendMessage () allows you to process Message objects (messages can contain data ,)

MyThread m = new MyThread ();

New Thread (m). start ();

}

/**

* Receives and processes the message. The Handler runs together with the current main thread.

**/

Class MyHandler extends Handler {

Public MyHandler (){

}

Public MyHandler (low.l ){

Super (L );

}

// Subclass must override this method to accept data

@ Override

Public void handleMessage (Message msg ){

// TODO Auto-generated method stub

Log. d ("MyHandler", "handleMessage ......");

Super. handleMessage (msg );

// The UI can be updated here

Bundle B = msg. getData ();

String color = B. getString ("color ");

MyHandlerActivity. this. button. append (color );

}

}

Class MyThread implements Runnable {

Public void run (){

Try {

Thread. sleep (10000 );

} Catch (InterruptedException e ){

// TODO Auto-generated catch block

E. printStackTrace ();

}

Log. d ("thread...", "mThread ........");

Message msg = new Message ();

Bundle B = new Bundle (); // store data

B. putString ("color", "my ");

Msg. setData (B );

MyHandlerActivity. this. myHandler. sendMessage (msg); // send a message to Handler to update the UI

}

}
}

Logoff

In fact, every Thread in Android is followed by a Looper. Looper Can help the Thread maintain a message queue. This concept is mentioned in yesterday's problem "Can't create handler inside thread, but logoff has nothing to do with Handler. We can see from the open source code that Android also provides a Thread inheritance class HanderThread to help us deal with it, in the HandlerThread object, you can use the getLooper method to obtain a Looper object control handle. We can map this Looper object to a Handler to implement a thread synchronization mechanism, the logoff object needs to be initialized for execution. the prepare method is the problem we saw yesterday. At the same time, we need to release resources and use logoff. the release method.

Logoff is the manager of MessageQueue. Each MessageQueue cannot be separated from the logoff object. The creation of the logoff object is implemented through the prepare function. At the same time, each logoff object is associated with a thread. You can call lorule. mylorule () to obtain the lorule object of the current thread.
Create a MessageQueue object when creating a logoff object. Besides the default logoff for the main thread, other threads do not have MessageQueue objects by default. Therefore, messages cannot be accepted. If you need to accept it, define a Looper object (through the prepare function) by yourself, so that the thread has its own Looper object and MessageQueue data structure.
Logoff extracts the Message from MessageQueue and submits it to handleMessage of Handler for processing. After the processing is complete, call Message. recycle () to put it into the Message Pool.

Message

For Android, Handler can pass some content, and the Bundle object can encapsulate String, Integer, and Blob binary objects, we use the sendEmptyMessage or sendMessage method of the Handler object in the thread to transmit a Bundle object to the Handler processor. The Handler class provides the override method handleMessage (Message msg) to determine, and identify each piece of information through msg. what. Unpackage Bundle to update the content in the UI thread of the Handler class to refresh the control. Related Handler objects related to sendXXXX message sending methods are as follows, and there are postXXXX related methods. These are basically the same as those in Win32. One is to directly return after sending, and the other is to return after processing.

Message: the Message object, which is stored in the Message Queue. A Message Queue contains multiple messages. Obtain the object of the Message instance, usually using the static method obtain () in the Message class. This method has multiple overloaded versions to choose from; it does not necessarily create a new instance directly. Instead, it first checks whether there is any available Message instance from the Message Pool. If yes, It is retrieved and returned. If no Message instance is available in the Message Pool, a Message object is created with the given parameters. When removeMessages () is called, the Message is deleted from the Message Queue and put into the Message Pool. In addition to the above method, you can also get a Message instance through the obtainMessage () of the Handler object.

Final boolean
SendEmptyMessage (int what)
 
Final boolean
SendEmptyMessageAtTime (int what, long uptimeMillis)
 
Final boolean
SendEmptyMessageDelayed (int what, long delayMillis)
 
Final boolean
SendMessage (Message msg)
 
Final boolean
SendMessageAtFrontOfQueue (Message msg)
 
Boolean
SendMessageAtTime (Message msg, long uptimeMillis)
 
Final boolean
SendMessageDelayed (Message msg, long delayMillis)
 

MessageQueue

It is a data structure, known as a message queue, where messages are stored. Each thread can have at most one MessageQueue data structure.
MessageQueue is not automatically created when a thread is created. A logoff object is usually used to manage the MessageQueue of the thread. When the main thread is created, a default logoff object is created, and a Message Queue is automatically created when the logoff object is created. Other non-main threads do not automatically create logoff. When necessary, they are implemented by calling the prepare function.
Java. util. concurrent object analysis

Programmers engaged in Java development in the past will not be unfamiliar with the Concurrent object. He is an important feature added after JDK 1.5 as a handheld device, and we do not advocate the use of this class, considering that Android has designed a Task mechanism for us, the Android development network does not repeat it too much here.

Task and AsyncTask

Android also provides a processing method different from the thread, namely Task and AsyncTask. From the open source code, we can see that it is a Concurrent encapsulation, developers can easily process these asynchronous tasks. Of course, there are still many methods and techniques involved in synchronization mechanisms, so I will not describe too much about the time and space issues.

 

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.