Android Handler Simple Example

Source: Internet
Author: User

Package Com.firstapp.foo.firstapp;import Android.os.handler;import android.os.message;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.util.log;import Android.widget.button;import android.widget.progressbar;import android.widget.textview;import java.util.Date; Public classThreaddemoactivity extends Appcompatactivity {Private StaticFinal String TAG ="Foo"; PrivateProgressBar Bar; PrivateButton Btnstartthread; PrivateTextView tvmsg; PrivateHandler Handler; @Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Handler=NewMyHandler ();        Setcontentview (R.layout.activity_thread_demo); Bar=(ProgressBar) Findviewbyid (R.id.progressbar); Btnstartthread=(Button) Findviewbyid (R.id.btnstartthread); Tvmsg=(TextView) Findviewbyid (r.id.tvmsg); Btnstartthread.setonclicklistener (v- {            NewThread ((){                 for(intI=0; i< -; i++) {bar.setprogress (i); Try{Thread.Sleep ( -); } Catch(interruptedexception e) {e.printstacktrace (); } log.i (TAG,"Thread Info:"+i); } Bundle Bundle=NewBundle (); Bundle.putstring ("msg","Hello"); //Other ...Message message =Handler.obtainmessage (); Message.what=2;                Message.setdata (bundle);                Handler.sendmessage (message); /*If the message has no additional parameters except the message code, the following sentence is more convenient*/                //Handler.sendemptymessage (2);}). Start ();    }); }    classMyHandler extends Handler {@Override Public voidhandlemessage (Message msg) {Switch(msg.what) { Case 2: Bundle Data=Msg.getdata (); String txt= Data.getstring ("msg"); Tvmsg.settext (TXT+", Thread completion:"+NewDate (). toString ());  Break; }        }    }}

Android Handler Simple Example

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.