WEB开发网
开发学院手机开发Android 开发 Android 线程超时的例子 阅读

Android 线程超时的例子

 2010-11-05 00:56:40 来源:WEB开发网   
核心提示:private Button button;private Timer timer;private final int TIMER_EXECUTE = 1;private final int ERROR_MESSAGE = 1;private final int CHECK_TIME = 5000;private ET

private Button button;

private Timer timer;

private final int TIMER_EXECUTE = 1;

private final int ERROR_MESSAGE = 1;

private final int CHECK_TIME = 5000;

private EThread eThread;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

button = (Button) findViewById(R.id.btn);

button.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

//timer for check the thread

timer = new Timer();

timer.schedule(new TimerTask(){

@Override

public void run() {

checkThread();

}

},CHECK_TIME);

eThread = new EThread();

eThread.start();

}

});

}

@Override

protected Dialog onCreateDialog(int id) {

return new AlertDialog.Builder(this).setTitle("错误")

.setMessage("线程超时!").create();

}

private Handler mHandler = new Handler() {

public void handleMessage(Message msg) {

switch(msg.what){

case TIMER_EXECUTE:

if (eThread.getState().toString().equals("TERMINATED")||

eThread.getState().toString().equals("TIMED_WAITING")) {

eThread.stopThread(true);

showDialog(ERROR_MESSAGE);

timer.cancel();// 关闭计时器

}

break;

}

super.handleMessage(msg);

}

};

protected void checkThread() {

Message msg = new Message();

msg.what = TIMER_EXECUTE;

mHandler.sendMessage(msg);

}

class EThread extends Thread {

private boolean flag = true;

public void stopThread(boolean flag) {

上一页  1 2 3 4  下一页

Tags:Android 线程 超时

编辑录入:coldstar [复制链接] [打 印]
赞助商链接