Android訊息機制——時鐘顯示和非同步處理工具類(AsyncTask)

來源:互聯網
上載者:User

標籤:

1. 時鐘顯示

定義布局檔案——activity_my_analog_clock_thread_demo.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns: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" >    <AnalogClock         android:id="@+id/myAnalogClock"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/>    <TextView        android:id="@+id/info"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /></LinearLayout>

定義Activity程式,進行操作

package com.example.contactsdemo;import java.text.SimpleDateFormat;import java.util.Date;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.Menu;import android.view.MenuItem;import android.widget.TextView;public class MyAnalogClockThreadDemo extends ActionBarActivity {    private TextView info = null;    //文本顯示組件    private static final int SET = 1;  //線程標記    private Handler handler = new Handler(){        @Override        public void handleMessage(Message msg) {            switch(msg.what){            case SET:    //判斷標誌位                MyAnalogClockThreadDemo.this.info.                setText("目前時間為:"+msg.obj.toString());  //設定顯示資訊            }        }            };    private class ClockThread implements Runnable{        @Override        public void run() {            while(true){                Message msg = MyAnalogClockThreadDemo.this.handler                        .obtainMessage(MyAnalogClockThreadDemo.SET,                                new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date())); //執行個體化Message                MyAnalogClockThreadDemo.this.handler.sendMessage(msg);  //發送訊息                try {                    Thread.sleep(1000);     //延遲1秒                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }             }                    }            }        @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_my_analog_clock_thread_demo);        this.info = (TextView) super.findViewById(R.id.info);  //取得組件        new Thread(new ClockThread()).start();    //啟動線程    }    @Override    public boolean onCreateOptionsMenu(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 boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}
2. 非同步處理工具類:AsyncTask——實現進度條

定義布局檔案——activity_my_async_task_demo.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns: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" >    <ProgressBar         android:id="@+id/bar"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        style="?android:attr/progressBarStyleHorizontal"/>    <TextView        android:id="@+id/info"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /></LinearLayout>

定義Activity程式,顯示進度條

package com.example.contactsdemo;import android.support.v7.app.ActionBarActivity;import android.os.AsyncTask;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.widget.ProgressBar;import android.widget.TextView;public class MyAsyncTaskDemo extends ActionBarActivity {    private ProgressBar bar = null;    //進度條組件    private TextView info = null;    //文本顯示組件        @Override    protected void onCreate(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 = new ChildUpdate();  //子任務對象        child.execute(100);  //休眠時間    }    private class ChildUpdate extends AsyncTask<Integer, Integer, String>{        @Override        protected void onPostExecute(String result) {  //任務執行完後執行            MyAsyncTaskDemo.this.info.setText(result); //設定文本        }        @Override        protected void onProgressUpdate(Integer... values) { //每次更新後的數值            MyAsyncTaskDemo.this.info.setText("當前進度是:"+values[0]); //更新文本資訊        }        @Override        protected String doInBackground(Integer... arg0) {  //處理背景工作            for(int i=0;i<100;i++){                            //進度條累加                MyAsyncTaskDemo.this.bar.setProgress(i);  //設定進度                this.publishProgress(i);  //傳遞每次更新的內容                try {                    Thread.sleep(arg0[0]);  //延緩執行                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            return "執行完畢!";        }            }    @Override    public boolean onCreateOptionsMenu(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 boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}

 

Android訊息機制——時鐘顯示和非同步處理工具類(AsyncTask)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.