Package Com.example.testhandler;
import Android.os.Bundle;
import Android.os.Handler;
import Android.os.Message;
import android.app.Activity;
//handler Common methods:
//1 post ()
//2 postdelayed ()
//3 SendMessage ()
//4 handlemessage ()
public class Mainactivity extends activity {
Runnable updaterunnable;
private final int cancel_runnable=99;
@Override
public void OnCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
final Handler handler=new Handler () {
@Override
public void Handlemessage (msg) {
super.handlemessage (msg);
//Below is the first of handler: according to the What of the message to make the corresponding processing
if (msg.what==1) {
System.out.println ("received message");
}
//above for handler the first: according to the message what different to make the corresponding treatment
//below: Handler second: handler.postdelayed (Runnable, Delaymillis)
if (msg.what==cancel_runnable) {
System.out.println ("current message msg.what=" +msg.what);
//Cancellation of runnable execution
removecallbacks (updaterunnable);
}
//Above are: Handler second: handler.postdelayed (Runnable, Delaymillis)
}
};
/////////////////////////////////////////////////////////////////////////////////////////////
//below: Handler first: send a message
New Thread () {
@Override
public void Run () {
message Message1=new message ();
message1.what=1;
message1.obj=new Object ();
//handle emits a Message object
//To facilitate testing to annotate the sentence
Handler.sendmessage (MESSAGE1);
Super.run ();
}
};
//above as: Handler first: send a message
//below: Handler second: handler.postdelayed (Runnable, Delaymillis)
//Issued runnable will delay the execution of a certain amount of time in the handler bound thread
updaterunnable = new Runnable () {
public void Run () {
for (int i = 5; i < i++) {
System.out.println ("i= in Runnable" +i);
}
}
};
//handle emits a Runnable object
//To facilitate testing to
the following two sentences
//cannot use Handler.post (updaterunnable);
//should use Handler.postdelayed (updaterunnable, 5000);
//Then sends a message immediately so that it can be
in Handlemessage
//Call Removecallbacks () method
handler.postdelayed (updaterunnable, 1000);
handler.sendemptymessage (cancel_runnable);
These are: Handler second: handler.postdelayed (Runnable, Delaymillis)
//below: Handler third: Handler.post (Runnable)
The
//emitted runnable executes immediately in the handler-bound thread
//To facilitate testing to comment on the following sentence code
//handler.post (updaterunnable);
//above as: Handler third: Handler.post (Runnable)
}
}