Android Development in Looper.prepare () and Looper.loop () _android

Source: Internet
Author: User

When do I need looper?

Looper is used to encapsulate the message loop in an Android thread, by default a thread does not have a message loop, and calls Looper.prepare () to create a message loop to the thread, calling Looper.loop () To make the message loop work, you can use Looper.prepare () and Looper.loop () to create a message queue to have message processing complete in that thread.

What to pay attention to using Looper

The code written after Looper.loop () is not executed immediately, and after the call Mhandler.getlooper (). Quit (), the loop is aborted, and the code behind it can be run. The Looper object holds messages and events through MessageQueue. A thread can have only one looper, corresponding to a MessageQueue.

For example, the following code will not execute until code 2 is called Getlooper (). Quit ().

Class Looperthread extends Thread
{
4 public void Run () 
{
looper.prepare ();
Code 1 ....
Looper.loop ();
Code 2 ...
} 
}

Beware of memory leaks caused by threads not being terminated; For example, a thread that associates a lifecycle over activity in an activity, remembering to end the thread when exiting the activity. A typical example is the Handlerthread run method is a dead loop, it does not end itself, the thread's lifecycle exceeds the activity lifecycle, and we must manually move thread.getlooper () in the activity's destruction method. Quit (): no leaks.

Looper and activity

The Mainui thread of the activity defaults to a message queue. So when you create a new handler in an activity, you don't need to call Looper.prepare () first.

The Looper.loop () in the main thread has been infinite loop why does it not cause ANR

Activitythread.java is the main thread entry class, where you can see the usual main method of writing Java programs, and the main method is the entrance to the entire Java program.

Activitythread Source

public static final void main (string[] args) {
...
Create Looper and MessageQueue
Looper.preparemainlooper ();
...
Polling begins polling
Looper.loop ();
...
}

Looper.loop () method

while (true) {
///Remove Message Queue messages, may block message
msg = Queue.next ();//might blocks
...
Parsing messages, distributing messages
msg.target.dispatchMessage (msg);
...
}

The main method of Activitythread is to do the message loop, and once you exit the message loop, your application exits. So why doesn't this dead loop cause ANR anomalies?

Because Android is event-driven, Looper.loop () constantly receives events, handles events, each click-Touch or Activity lifecycle is run under Looper.loop (), and if it stops, the application stops. It can only be a message or the processing of the message blocks Looper.loop () rather than looper.loop () blocking it. It is also said that our code is actually in this loop to execute, of course, will not block.

Handlemessage method Part of the source code

public void Handlemessage (message msg) {if (debug_messages) slog.v (TAG, ">>> handling:" + codetostring (Msg.wha
t)); Switch (msg.what) {case launch_activity: {trace.tracebegin (Trace.trace_tag_activity_manager, "Activitystart"); final
Activityclientrecord r = (Activityclientrecord) msg.obj;
R.packageinfo = Getpackageinfonocheck (R.activityinfo.applicationinfo, r.compatinfo);
Handlelaunchactivity (R, NULL);
Trace.traceend (Trace.trace_tag_activity_manager);
} break;
Case relaunch_activity: {trace.tracebegin (Trace.trace_tag_activity_manager, "Activityrestart");
Activityclientrecord r = (Activityclientrecord) msg.obj;
Handlerelaunchactivity (R);
Trace.traceend (Trace.trace_tag_activity_manager);
} break;
Case PAUSE_ACTIVITY:Trace.traceBegin (Trace.trace_tag_activity_manager, "activitypause");
Handlepauseactivity ((IBinder) Msg.obj, False, (MSG.ARG1 & 1)!= 0, Msg.arg2, (MSG.ARG1 & 2)!= 0);
Maybesnapshot ();
Trace.traceend (Trace.trace_tag_activity_manager);
Break Case Pause_ACTIVITY_FINISHING:Trace.traceBegin (Trace.trace_tag_activity_manager, "activitypause");
Handlepauseactivity ((IBinder) Msg.obj, True, (Msg.arg1 & 1)!= 0, Msg.arg2, (MSG.ARG1 & 1)!= 0);
Trace.traceend (Trace.trace_tag_activity_manager);
Break
...........
} }

It can be seen that the life cycle of activity depends on the looper.loop of the main thread, and the corresponding measures are adopted when different message is received.

If a message processing time is too long, such as you in OnCreate (), Onresume () inside processing time-consuming operations, then the next message such as the user's Click event can not be processed, the whole cycle will produce cotton, a long time to become a ANR.

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.