Android Handler,looper,message

Source: Internet
Author: User

To do a simple little demo about Handler,looper,message, a button on the main interface of the code, click Send Message (accumulate) to the thread's Looper loop, and then print it out in Logcat:

Package Zhangphil.looper;import Android.os.bundle;import Android.os.handler;import android.os.looper;import Android.os.message;import Android.util.log;import Android.view.view;import Android.widget.button;import Android.app.activity;public class Mainactivity extends Activity {private Handler mhandler;private final int message_what = 101; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); final button button = (button) Findviewbyid (R.id.button); Button.setonclicklistener (New View.onclicklistener () {private int count = 0; @Overridepublic void OnClick (View v) { Mhandler.obtainmessage (Message_what, Count). Sendtotarget (); Button.settext ("Sent" + count); count++;}); New Messagereceivethread (). Start ();} Private class Messagereceivethread extends Thread {@Overridepublic void run () {looper.prepare (); mhandler = new Handler () { @Overridepublic void Handlemessage (Message msg) {switch (msg.what) {case message_what:string TeXT = Msg.obj + ""; LOG.D ("Received--", text); break;}}; Looper.loop ();}}}

Activity_main.xml files required by Mainactivity.java:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:layout_width= "Match_ Parent "    android:layout_height=" match_parent ">    <button        android:id=" @+id/button "        android: text= "Send Message"        android:layout_width= "wrap_content"        android:layout_height= "Wrap_content"        android: Layout_centerhorizontal= "true"        android:layout_centervertical= "true"/></relativelayout>



Android Handler,looper,message

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.