Android Messaging mechanism-clock display and asynchronous Processing tool Class (Asynctask)

Source: Internet
Author: User

1. Clock display

Defining Layout Files--activity_my_analog_clock_thread_demo.xml

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"android:orientation= "vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"Android:paddingbottom= "@dimen/activity_vertical_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Tools:context= "Com.example.contactsdemo.MyAnalogClockThreadDemo" >    <AnalogClockAndroid:id= "@+id/myanalogclock"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"/>    <TextViewAndroid:id= "@+id/info"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content" /></LinearLayout>

Define the activity program and do the operation

 PackageCom.example.contactsdemo;ImportJava.text.SimpleDateFormat;Importjava.util.Date;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.widget.TextView; Public classMyanalogclockthreaddemoextendsactionbaractivity {PrivateTextView info =NULL;//Text Display component    Private Static Final intSET = 1;//thread Tagging    PrivateHandler Handler =NewHandler () {@Override Public voidhandlemessage (Message msg) {Switch(msg.what) { CaseSET://judging the flag bitMyanalogclockthreaddemo. This. Info. SetText ("Current Time:" +msg.obj.tostring ());//Setting Display information            }        }            }; Private classClockthreadImplementsrunnable{@Override Public voidrun () { while(true) {Message msg= Myanalogclockthreaddemo. This. Handler. Obtainmessage (Myanalogclockthreaddemo.set,NewSimpleDateFormat ("Yyyy-mm-dd hh-mm-ss"). Format (NewDate ()));//Instantiate a messageMyanalogclockthreaddemo. This. Handler.sendmessage (msg);//Send Message                Try{Thread.Sleep (1000);//1 seconds Delay}Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }} @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_my_analog_clock_thread_demo);  This. info = (TextView)Super. Findviewbyid (R.id.info);//Get Components        NewThread (NewClockthread ()). Start ();//Start Thread} @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.my_analog_clock_thread_demo, menu); return true; } @Override Public Booleanonoptionsitemselected (MenuItem item) {//Handle Action Bar item clicks here. The Action Bar would//automatically handle clicks on the Home/up button, so long//As you specify a the parent activity in Androidmanifest.xml.        intID =Item.getitemid (); if(id = =r.id.action_settings) {            return true; }        return Super. onoptionsitemselected (item); }}
2. Asynchronous processing Tool Class: asynctask--implementation progress bar

Defining Layout Files--activity_my_async_task_demo.xml

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"android:orientation= "vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"Android:paddingbottom= "@dimen/activity_vertical_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Tools:context= "Com.example.contactsdemo.MyAsyncTaskDemo" >    <ProgressBarAndroid:id= "@+id/bar"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"style= "? Android:attr/progressbarstylehorizontal"/>    <TextViewAndroid:id= "@+id/info"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content" /></LinearLayout>

Define activity program, show progress bar

 PackageCom.example.contactsdemo;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.os.AsyncTask;ImportAndroid.os.Bundle;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.widget.ProgressBar;ImportAndroid.widget.TextView; Public classMyasynctaskdemoextendsactionbaractivity {PrivateProgressBar bar =NULL;//Progress bar Component    PrivateTextView info =NULL;//Text Display component@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_my_async_task_demo);  This. Bar = (ProgressBar)Super. Findviewbyid (R.id.bar);  This. info = (TextView)Super. Findviewbyid (R.id.info); Childupdate Child=NewChildupdate ();//Child Task ObjectChild.execute (100);//Sleep Time    }    Private classChildupdateextendsAsynctask<integer, Integer, string>{@Overrideprotected voidOnPostExecute (String result) {//execute after the task is finishedMyasynctaskdemo. This. Info.settext (Result);//Set Text} @Overrideprotected voidOnprogressupdate (Integer ... values) {//the value after each updateMyasynctaskdemo. This. Info.settext ("Current progress is:" +values[0]);//Update text Information} @OverrideprotectedString doinbackground (Integer ... arg0) {//working with background tasks             for(inti=0;i<100;i++) {//Progress bar AccumulationMyasynctaskdemo. This. bar.setprogress (i);//Set Progress                 This. publishprogress (i);//deliver content for each update                Try{thread.sleep (arg0[0]);//deferred execution}Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }            return"Execution is complete!" "; }} @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.my_async_task_demo, menu); return true; } @Override Public Booleanonoptionsitemselected (MenuItem item) {//Handle Action Bar item clicks here. The Action Bar would//automatically handle clicks on the Home/up button, so long//As you specify a the parent activity in Androidmanifest.xml.        intID =Item.getitemid (); if(id = =r.id.action_settings) {            return true; }        return Super. onoptionsitemselected (item); }}

Android Messaging mechanism-clock display and asynchronous Processing tool Class (Asynctask)

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.