1. Take a look at the simplest example of a progress bar
EG:
Package com.sxz.android.thread;
Import Java.util.concurrent.atomic.AtomicBoolean;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.widget.ProgressBar;
public class Handlerdemo extends Activity {
ProgressBar Bar;
Atomicboolean isrunning = new Atomicboolean (false);
Handler Mhandler = new Handler () {
@Override
public void Handlemessage (Message msg) {
Bar.incrementprogressby (5);
}
};
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.my_progressbar);
Bar = (ProgressBar) Findviewbyid (R.ID.PROGRESSBAR1);
}
@Override
protected void OnStart () {
Super.onstart ();
Thread myThread = new Thread (new Runnable () {
@Override
public void Run () {
try {
for (int i = 0; i < && isrunning.get (); i++) {
Message msg = Mhandler.obtainmessage ();
Thread.Sleep (500);
Msg.sendtotarget ();
}
} catch (Throwable t)
{
}
}
});
Isrunning.set (TRUE);
Mythread.start ();
}
@Override
protected void OnStop () {
Super.onstop ();
Isrunning.set (FALSE);
}
}
2. Basic Concepts
MessageQueue Message Queuing, where messages are stored, executed according to FIFO rules, each thread can only have one MessageQueue, in the creation Looper Object creates a MessageQueue object. and MessageQueue
The
will have a corresponding handler,handler that will send the message to MessageQueue in two ways.
①sendmessage. A Message object is sent through SendMessage and is handled by Handler's Handlemessage () function.
②post sends a Runnable object through the Post method, it executes itself.
Both messages are inserted at the end of the MessageQueue and are executed in a first-in-one-out manner. But the way messages are sent out in these two ways can be slightly different.
The
message messages object that is stored in the MessageQueue. A MessageQueue can contain multiple message objects. The Message object can be obtained by message.obtain () or handler.obtainmessage (). But this does not necessarily mean creating a new instance directly. Instead, you'll see if there are any message instances available from the message pool. The instance is returned directly after being removed. If there is no message instance available in the messaging pool, a message object is created with the given parameters. When Removemessage () is called, the message is removed from the MessageQueue and placed into the message pool. The
message can actually be understood as information exchanged between threads, and the processing of a data background thread requires updating the UI, and sending a message contains some data to the UI thread.
Looper operation MessageQueue, one Looper corresponds to one MessageQueue. by calling Looper.mylooper (), you can get the current thread's The Looper object. Looper Remove the message from the MessageQueue and leave it to Handler's handlemessage () for processing. When processing is complete, call Message.recycle () to put it in the message pool.
Looper is the steward of the MessageQueue of every line thread. Android does not have Gloabal MessageQueue, and Android automatically builds MessageQueue for the main thread (UI thread), but MessageQueue is not established on the thread of the strands. So calling Looper.getmainlooper () gets the main thread Looper not NULL, but the Looper called Looper.mylooper () can be null.
Summary: The relationship between several people:
The processor of the Handler message.
Handler is responsible for encapsulating the information that needs to be passed into a message object,
Then call the SendMessage () method to put the message into the MessageQueue,
When MessageQueue loops to the Message,
Call the Handlemessage () method of the corresponding handler object to process it.
Handler can share the same Looper and MessageQueue.
3. Handler.post (r) The same thread of doubt
Handler.post (R) adds r to the message queue, but does not open a new thread. It is not executed until the message is removed.
PackageCom.lei.handlethread;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;Importandroid.app.Activity;ImportAndroid.view.Menu;ImportAndroid.widget.Button;PublicClass MainactivityExtendsActivity {Private Button BTN =Null;Private Handler Handler =NewHandler (); @OverridePublicvoidOnCreate (Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Handler.post (R); Setcontentview (R.layout.activity_main); BTN =(Button) Findviewbyid (R.id.hello);//used to verify that Setcontentview () is executed first.
String s=(String) Btn.gettext ();//
System.out.println (s); SYSTEM.OUT.PRINTLN ("Activity--->" +Thread.CurrentThread (). GetId ()); System.out.println ("Activityname--->" +Thread.CurrentThread (). GetName ()); } Runnable R =NewRunnable () {PublicvoidRun () {System.out.println ("Handler--->" +thread.currentthread (). GetId ()); System.out.println ("HandlerName--->" +thread.currentthread (). GetName ()); try {Thread.Sleep (10000catch (Interruptedexception e) {// TODO auto-generated catch Block E.printstacktrace () ; } } }; @Override public boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.activity_main, menu); return true
Run Result: Logcat Print the following information first. Program Run Interface 10s display TextView text.
Explain:
The main thread extracts a message from the message pump, processes (executes the related function), and then takes one, processing. SoonCreate是某一消息处理中的执行,其中post一个消息,只是把消息加入队列了,还没执行新消息,什么时候执行?要等前一个消息处理完,再次从消息泵中取消息处理时,它才被执行。所以先是main的system.out,再是post的system.out
相比之下,sendMessage是同步执行,用handler.sendMessage,那顺序就变了。
As for Setcontentview (R.layout.activity_main), it is definitely the first to execute, the program interface opens first, but the interface space is not displayed until the activity's resume (that is, the interaction phase) stage.
By obtaining an interface space ID, you can verify that the space content is printed in log.
Thread,handler,loop Learning in Android