Handler and callback mechanism in Android--Iteye technology website
The handler is primarily used to communicate between threads in a mechanism. If you need to accept messages from other threads in the activity or service, you need to implement the Handler.callback interface in the activity or service that needs to receive the message to implement this interface:
Java code ?
- public? booleanhandlemessage (? Message?inmessage?)? ;??
public boolean handlemessage (Message inmessage);
?
Method. An instance of the class that implements the callback is then passed in where the handler is created:
Java code ?
- Looper?? Looper?=?incontext.getmainlooper ();??
- Mthread?=?looper.getthread ();??
- Mhandler?=? new? Handler (Looper?,? mcallback?);??
Looperlooper = Incontext.getmainlooper (); mthread = Looper.getthread (); mhandler = new Handler (Looper, mcallback);
?
Or:
Java code ?
- Mhandler?=? new? Handler (? mcallback?)??
Mhandler = new Handler (mcallback)
?
You can then send a message to the Acitity or service using the following code in the thread:
Java code ?
- //intoken? is an object that can pass in other parameters ??
- Mhandler.obtainmessage (inwhat?,? inA?,? inB?,? intoken?)??
- Mhandler.sendmessage (? inmessage?)??
Intoken is an object that can pass in other parameters Mhandler.obtainmessage (Inwhat, InA, InB, Intoken) mhandler.sendmessage (inmessage)
?
? or
Java code ?
- Mhandler.sendemptymessage (? inwhat?)??
Mhandler.sendemptymessage (Inwhat)
?
When the above code is taken, the handlemessage using the callback instance will be called when the handler is created.
?
You can use the following code to put a thread instance into handler for it to execute:
Java code ?
- Mhandler.post (? inrunnable?);???
?
You can delete this thread using the following code:
Java code ?
- Mhandler.removecallbacks (? inrunnable?);???
? There are many similar ways to send messages or add threads on handler. Added some other features.
Handler and callback mechanisms in Android