package com.android.test;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class HandlerTestActivity extends Activity {
private static final String TAG = "HandlerTest";
private MyHandler myhandler;
//声明2个按钮控件
private Button startBtn = null;
private Button endBtn = null;
private ProgressBar bar = null;
private Thread thread;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bar = (ProgressBar)findViewById(R.id.progbar);
startBtn = (Button)findViewById(R.id.startBtn);
endBtn = (Button)findViewById(R.id.endBtn);
startBtn.setOnClickListener(new StartButtonListener());
endBtn.setOnClickListener(new EndButtonListener());
myhandler = new MyHandler();
//myhandler.post(updateRunnable);
MyThread mythread = new MyThread();
thread = new Thread(mythread);
Log.d(TAG,"onCreate()");
Log.d(TAG,"activity--->" + Thread.currentThread().getId());
Log.d(TAG,"activityname--->" + Thread.currentThread().getName());
}
class StartButtonListener implements OnClickListener
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
bar.setVisibility(View.VISIBLE);
thread.start();
}
}
class EndButtonListener implements OnClickListener
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//myhandler.removeCallbacks(updateRunnable);
thread.destroy();
}
}
class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
bar.setProgress(msg.arg1);
Log.d(TAG,"MyHandler--->handleMessage()");
}
}
public class MyThread implements Runnable{
int i = 0;
@Override
public void run() {
// TODO Auto-generated method stub
Log.d(TAG,"updateRunnable--->run()");
Log.d(TAG,"runnable--->" + Thread.currentThread().getId());
Log.d(TAG,"runnable name--->" + Thread.currentThread().getName());
do{
if(i==100)
{
break;
}
i = i+ 10;
Message msg = myhandler.obtainMessage();
msg.arg1 = i;
try{
Thread.sleep(1000);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
myhandler.sendMessage(msg);
}while(true);
}
}