import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int TIME_OUT = 0 ;
private static final int SUCCESS = 1 ;
// 超時的時限為5秒
private static final int TIME_LIMIT = 5000 ;
ProgressDialog proDialog;
Timer timer;
Thread thread;
Button btn1, btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
// 測試未超時的線程,,為btn1綁定事件
btn1.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
proDialog = ProgressDialog.show(MainActivity. this , "提示" ,
"線程運行中" );
// 匿名內(nèi)部線程
thread = new Thread() {
@Override
public void run() {
while ( true ) {
try {
//線程休眠時間,超時
sleep( 10000 );
} catch (InterruptedException e) {
break ;
}
}
}
};
thread.start();
// 設(shè)定定時器
timer = new Timer();
timer.schedule( new TimerTask() {
@Override
public void run() {
sendTimeOutMsg();
}
}, TIME_LIMIT);
}
});
// 測試超時的線程,為btn2綁定事件
btn2.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
proDialog = ProgressDialog.show(MainActivity. this , "提示" ,
"線程運行中" );
// 匿名內(nèi)部線程
thread = new Thread() {
public void run() {
try {
// 線程休眠時間,,未超時
Thread.sleep( 3000 );
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msgSuc = new Message();
msgSuc.what = SUCCESS;
myHandler.sendMessage(msgSuc);
}
};
thread.start();
// 設(shè)定定時器
timer = new Timer();
timer.schedule( new TimerTask() {
@Override
public void run() {
sendTimeOutMsg();
}
}, TIME_LIMIT);
}
});
}
// 接收消息的Handler
final Handler myHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case TIME_OUT:
//打斷線程
thread.interrupt();
proDialog.dismiss();
Toast.makeText(MainActivity. this , "線程超時" , Toast.LENGTH_SHORT)
.show();
break ;
case SUCCESS:
//取消定時器
timer.cancel();
proDialog.dismiss();
Toast.makeText(MainActivity. this , "線程運行完成" , Toast.LENGTH_SHORT)
.show();
break ;
default :
break ;
}
};
};
//向handler發(fā)送超時信息
private void sendTimeOutMsg() {
Message timeOutMsg = new Message();
timeOutMsg.what = TIME_OUT;
myHandler.sendMessage(timeOutMsg);
}
}
|