In Android, messages are often used during information interaction between threads or threads. If we are familiar with the Internal principles of these basic things, it will make it easy and better for us to build a system, avoid some low-level errors. Before learning about the message mechanism in Android, we should first understand several message-related classes:
1. Message
A message object, as its name implies, is a class that records message information. This class has several important fields:
A. arg1 and arg2: We can use two fields to store the integer values we need to pass. in Service, we can store the Service ID.
B. obj: this field is of the Object type. We can use this field to transmit multiple entries to the receiver of the message.
C. what: this field can be said to be a message identifier. In message processing, we can perform different processing based on different values of this field, similar to when we are processing a Button event, switch (v. getId () determines which button is clicked.
When using Message, we can create a Message instance through new Message (). However, for Android, we recommend that you use Message. obtain () or Handler. obtainMessage () to obtain the Message object. This is not necessarily to create a new instance directly, but to check whether there is any available Message instance from the Message pool. If there is a Message instance, the instance is taken out and returned. If no Message instance is available in the Message pool, a new Message object is created based on the specified parameter. By analyzing the source code, we can know that the Android system instantiates 10 Message objects in the Message pool by default.
2. MessageQueue
View Code
A Message queue is used to store the data structure of a Message object and store messages according to the "first-in-first-out" principle. Storage does not actually mean saving, but concatenates Message objects in a linked list. The MessageQueue object does not need to be created by ourselves, but is managed by a loose object. A thread can have at most one MessageQueue. We can use logoff. myQueue () to obtain the MessageQueue in the current thread. 3. LooperMessageQueue manager. In a thread, if there is a loop object, there must be a MessageQueue object, and only one loop object and one MessageQueue object. In the Android system, except for the main thread, there is a default logoff object. By default, other threads do not have logoff objects. If we want the newly created thread to have a logoff object, we should first call The logoff. prepare () method, and then call the logoff. loop () method. Typical usage: class LooperThread extends Thread {public Handler mHandler; public void run () {loid. prepare (); // other operations to be processed logoff. loop ();}}
If there is a logoff object in our thread, we can get it through logoff. mylogoff (). In addition, we can get the logoff object of the main thread in the current application system through logoff. getmainlogoff. Note that if the logoff object is located in the main thread of the application, lorule. mylorule () and lorule. getmainlorule () obtain the same object.
4. Handler
Message processor. Through the Handler object, we can encapsulate the Message object, and then add the Message object to MessageQueue through sendMessage (msg); When MessageQueue loops to this Message, the handleMessage () method of the handler object corresponding to the Message object will be called to process it. Because the handleMessage () method processes messages, we should write a class that inherits from Handler and then process the required operations in handleMessage.
The following code is used to analyze how messages are processed in Android. First, paste the test code:
View Code
/*** @ Author coolszy * @ blog http://blog.csdn.net/coolszy ***/public class MessageService extends Service {private static final String TAG = "MessageService"; private static final int KUKA = 0; private Looper looper; private ServiceHandler handler;/*** because the processing of messages is in the handleMessage () method of Handler, We need to write our own class * inherited from the Handler class, then write the required function code in handleMessage () * @ author coolszy/private final class Service Handler extends Handler {public ServiceHandler (Looper loler) {super (logoff) ;}@ Override public void handleMessage (Message msg) {// determine which Message switch (msg) is based on what field. what) {case KUKA: // obtain the obj field of msg. We can compile the required function code Log here. I (TAG, "The obj field of msg:" + msg. obj); break; // other cases default: break;} // if our Service has completed the task, stop Service stopSelf (msg. arg1) ;}@ Override public void onCreate () {Log. I (TAG, "MessageService --> onCreate ()"); // by default, the Service runs in the main thread, and the Service is generally time-consuming, if // is placed in the main thread, the interaction between the program and the user will be affected. Therefore, put the Service // in a separate thread and execute HandlerThread thread = new HandlerThread ("MessageDemoThread", Process. THREAD_PRIORITY_BACKGROUND); thread. start (); // obtain the logoff object logoff = thread in the current thread. getLooper (); // create a Handler object and pass the logoff parameter so that handler, // logoff, and messageQueue are connected to handler = new ServiceHandler (loler );} @ Override public int onStartCommand (Intent intent, int flags, int startId) {Log. I (TAG, "MessageService --> onStartCommand ()"); // obtain a Message instance Message msg = handler from the Message pool. obtainMessage (); // arg1 stores the thread ID. In the handleMessage () method, // we can stop the service msg by using the stopSelf (startId) method. arg1 = startId; // msg flag of msg. what = KUKA; // here I create a date object, assign the value to the obj field // in reality, we can pass the object Date = new date (); msg through obj. obj = date; // Add msg to the MessageQueue handler. sendMessage (msg); return START_STICKY;} @ Override public void onDestroy () {Log. I (TAG, "MessageService --> onDestroy ()") ;}@ Override public IBinder onBind (Inten