Handler and callback mechanisms in Android

Source: Internet
Author: User

Http://alex-yang-xiansoftware-com.iteye.com/blog/850865

Handler is mainly used for communication between threads. If the activity or service needs to accept messages from other threads, the handler. Callback interface must be implemented in the activity or service that needs to receive messages. This interface is implemented:

Java code
  1. Public Boolean handlemessage (Message inmessage );

 

Method. Then, the callback class instance is passed in at the place where handler is created:

Java code
  1. Logoff logoff = incontext. getmainlogoff ();
  2. Mthread = logoff. getthread ();
  3. Mhandler = new handler (logoff, mcallback );

 

Or:

Java code
  1. Mhandler = new handler (mcallback)

 

Then, you can use the following code to send messages to acitity or service:

Java code
  1. // The token is an object that can be passed in with other parameters.
  2. Mhandler. obtainmessage (inwhat, INA, INB, Token Ken)
  3. Mhandler. sendmessage (inmessage)

 

Or

Java code
  1. Mhandler. sendemptymessage (inwhat)

 

After the preceding code is executed, the handlemessage of 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 execution:

Java code
  1. Mhandler. Post (inrunnable );

 

You can use the following code to delete this thread:

Java code
  1. Mhandler. removecallbacks (inrunnable );

Handler also has many similar methods to send messages or add threads. Added some other features

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.