Android消息机制——时钟显示和异步处理工具类(AsyncTask)

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);
    }
}
原文地址:https://www.cnblogs.com/gaopeng527/p/4595426.html