Android Development Notes: Message loop and logoff

Source: Internet
Author: User

Understanding Logoff
Logoff is a tool used to add a MessageQueue to a thread and wait cyclically. When there is a message, it will arouse the thread to process the message until the thread ends. Normally, logoff is not used, because for system components such as Activity and Service, Frameworks has initialized the thread (commonly known as the UI thread or main thread) for us and contains a logoff, and the message queue created by logoff, so the main thread will continue to run and process user events until some events (BACK) Exit.
If we need to create a new thread, and this thread needs to be able to process the message events sent by other threads cyclically, or to perform complex interaction with other threads for a long time, in this case, logoff is required to establish a message queue for the thread.
Logoff is also very simple, and there are few methods, the most important of which are four:
Public static prepare ();
Public static mylogoff ();
Public static loop ();
Public void quit ();
The usage is as follows:
1. Call lorule. prepare () in the run () method of each thread to initialize the message queue for the thread.
2. Call lorule. mylorule () to obtain the reference of this lorule object. This is not necessary, but if you need to save the logoff object, it must be after prepare (). Otherwise, the method called on this object may not be effective, such as logoff. quit () won't quit.
3. Add Handler in the run () method to process messages.
4. Add logoff. loop () call to start the thread's message queue and receive messages.
5. When you want to exit the message loop, call logoff. quit (). Note that this method is called on the object. Obviously, the object means to exit the specific logoff. If no other operation is performed in run (), the thread stops running.
Let's look at an instance.
Instance
This example provides a service for executing tasks: Copy codeThe Code is as follows: public class LooperDemoActivity extends Activity {
Private WorkerThread mWorkerThread;
Private TextView mStatusLine;
Private Handler mMainHandler;

@ Override
Public void onCreate (Bundle icicle ){
Super. onCreate (icicle );
SetContentView (R. layout. looper_demo_activity );
MMainHandler = new Handler (){
@ Override
Public void handleMessage (Message msg ){
String text = (String) msg. obj;
If (TextUtils. isEmpty (text )){
Return;
}
MStatusLine. setText (text );
}
};

MWorkerThread = new WorkerThread ();
Final Button action = (Button) findViewById (R. id. looper_demo_action );
Action. setOnClickListener (new View. OnClickListener (){
Public void onClick (View v ){
MWorkerThread.exe cuteTask ("please do me a favor ");
}
});
Final Button end = (Button) findViewById (R. id. looper_demo_quit );
End. setOnClickListener (new View. OnClickListener (){
Public void onClick (View v ){
MWorkerThread. exit ();
}
});
MStatusLine = (TextView) findViewById (R. id. looper_demo_displayer );
MStatusLine. setText ("Press 'Do me a favor' to execute a task, press 'end of Service' to stop looper thread ");
}

@ Override
Public void onDestroy (){
Super. onDestroy ();
MWorkerThread. exit ();
MWorkerThread = null;
}

Private class WorkerThread extends Thread {
Protected static final String TAG = "WorkerThread ";
Private Handler mHandler;
Private loopdomainmlow.gov.cn;

Public WorkerThread (){
Start ();
}

Public void run (){
// Attention: if you obtain lotain before looper # prepare (), you can still use the loill
// To process message even after you call loit # quit (), which means the Looper does not
// Really quit.
Logoff. prepare ();
// So we shocould call lould # myloway () after Looper # prepare (). Anyway, we shocould put all stuff between loway # prepare ()
// And logoff # loop ().
// In this case, you will receive "Handler {4051e4a0} sending message to a Handler on a dead thread
// 05-09 08:37:52. 118: W/MessageQueue (436): java. lang. RuntimeException: Handler {4051e4a0} sending message
// To a Handler on a dead thread ", when try to send a message to a low.which loit # quit () had called,
// Because the thread attaching the Looper and Handler dies once Loes # quit () gets called.
Mlogoff = logoff. mylogoff ();
// Either new Handler () and new Handler (mloler) will work
MHandler = new Handler (mloler ){
@ Override
Public void handleMessage (Message msg ){
/*
* Attention: object Message is not reusable, you must obtain a new one for each time you want to use it.
* Otherwise you got "android. util. AndroidRuntimeException: {what = 1000 when =-15 ms obj = it is my please
* To serve you, please be patient to wait !........ } This message is already in use ."
*/
// Message newMsg = Message. obtain ();
StringBuilder sb = new StringBuilder ();
Sb. append ("it is my please to serve you, please be patient to wait! \ N ");
Log. e (TAG, "workerthread, it is my please to serve you, please be patient to wait! ");
For (int I = 1; I <100; I ++ ){
Sb. append (".");
Message newMsg = Message. obtain ();
NewMsg. obj = sb. toString ();
MMainHandler. sendMessage (newMsg );
Log. e (TAG, "workthread, working" + sb. toString ());
SystemClock. sleep (100 );
}
Log. e (TAG, "workerthread, your work is done .");
Sb. append ("\ nyour work is done ");
Message newMsg = Message. obtain ();
NewMsg. obj = sb. toString ();
MMainHandler. sendMessage (newMsg );
}
};
Logoff. loop ();
}

Public void exit (){
If (mlogoff! = Null ){
Mloit. quit ();
Mlogoff = null;
}
}

// This method returns immediately, it just push an Message into Thread's MessageQueue.
// You can also call this method continuously, the task will be executed one by one in
// Order of which they are pushed into MessageQueue (they are called ).
Public void executeTask (String text ){
If (mloiter = null | mHandler = null ){
Message msg = Message. obtain ();
Msg. obj = "Sorry man, it is out of service ";
MMainHandler. sendMessage (msg );
Return;
}
Message msg = Message. obtain ();
Msg. obj = text;
MHandler. sendMessage (msg );
}
}
}

In this example, when a task is executed in the main thread only sends a Message to the service thread and transmits the relevant data, the data is packaged into a Message object ), then put it in the message queue of the service thread, and the call of the main thread returns, this process is very fast, so it will not block the main thread. Every time a message enters the message queue, the service thread is awakened to retrieve the message from the queue and then execute the task. The service thread can receive any number of tasks, that is, the main thread can continuously send messages to the service thread, these messages will be put into the message queue, the service thread executes them one by one until all tasks are completed (the message queue is empty and no other messages exist ), the service thread enters the sleep state again until a new message arrives.
If you want to terminate the service thread and call quit () on the mLooper object, the message loop is exited. Because the thread has no other operations, the whole thread is terminated.
It should be noted that when the message loop of a thread has exited, messages cannot be sent to it. Otherwise, an exception will throw "RuntimeException: handler {4051e4a0} sending message to a Handler on a dead thread ". Therefore, we recommend that you. after prepare (), call logoff. mylogoff () is used to obtain the reference to this logoff. First, it is used to terminate (quit () must be called on the object ); in addition, it is used to check whether the message cycle has exited when receiving messages (for example, above ).

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.