Android Handler简单示例

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 class ThreadDemoActivity extends AppCompatActivity {
    private static final String TAG = "foo";
    private ProgressBar bar;
    private Button btnStartThread;
    private TextView tvMsg;

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        handler = new MyHandler();
        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 -> {
            new Thread(()->{
                for (int i=0; i< 100; i++){
                    bar.setProgress(i);
                    try {
                        Thread.sleep(30);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.i(TAG, "Thread Info:" + i);
                }

                Bundle bundle = new Bundle();
                bundle.putString("msg","你好");
                // other ...
                Message message = handler.obtainMessage();
                message.what = 2;
                message.setData(bundle);
                handler.sendMessage(message);

                /* 若消息除消息码外,无附加参数,则下面一句更简便 */
                //handler.sendEmptyMessage(2);
            }).start();
        });
    }

    class MyHandler extends  Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 2:
                    Bundle data = msg.getData();
                    String txt = data.getString("msg");

                    tvMsg.setText(txt + ", 线程完成:" + new Date().toString() );
                    break;
            }
        }
    }
}

 

posted @ 2016-09-01 05:42  庚武  Views(614)  Comments(0Edit  收藏  举报