Android Handler简单例子

package com.example.handler;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    
    //声明变量
    private Button b1;
    private ProgressDialog pd;
    
    //定义Handler对象
    private Handler handler =new Handler(){
        @Override
        //当有消息发送出来的时候就执行Handler的这个方法
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            //只要执行到这里就关闭对话框
            pd.dismiss();
        }
    };
    
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        Resources res=  this.getResources();
        //查看UI组件所在的线程名
        Log.i("tag", "onCreate()-->"+Thread.currentThread().getName());
        
        //定义UI组件
        b1= (Button)findViewById(R.id.Button01);
        //给按钮绑定单击事件监听器
        b1.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                //点击按钮后去处理长耗时操作
                processThread();
            }
        });
    }
    
    
    private void processThread(){
        
        //构建一个下载进度条
        pd= ProgressDialog.show(MainActivity.this, "下载文件", "正在下载……");
        Log.i("tag", "processThread()-->"+Thread.currentThread().getName());
        
        new Thread(){
            
            @Override
            public void run(){
                Log.i("tag", "run()-->"+Thread.currentThread().getName());
                //在新线程里执行长耗时方法
                longTimeMethod();
                //执行完毕后给handler发送一个空消息
                handler.sendEmptyMessage(0);
            }
            
        }.start();
    }
    
    //模拟下载文件的长耗时方法
    private void longTimeMethod(){
        try {
            Log.i("tag", "longTimeMethod-->"+Thread.currentThread().getName());
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}



转自:http://android.yaohuiji.com/archives/770

你可能感兴趣的:(android,android,android,handler,handler)