.java
package com.example.mydemo; import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView; public class MainActivity extends Activity {
private TextView text_view = null;
private Button start = null;
private Button end = null;
private int count = 0;
// 使用handler时首先要创建一个handler
Handler handler = new Handler();
// 要用handler来处理多线程可以使用runnable接口,这里先定义该接口
// 线程中运行该接口的run函数
Runnable update_thread = new Runnable() {
public void run() {
// 线程每次执行时输出"UpdateThread..."文字,且自动换行
// textview的append功能和Qt中的append类似,不会覆盖前面
// 的内容,只是Qt中的append默认是自动换行模式
// text_view.append("\nUpdateThread...");
text_view.setText(String.valueOf(count++));
// 延时1s后又将线程加入到线程队列中
if (count >= 5) {
// handler.removeCallbacks(update_thread);//用此行停止不行,需要发消息外部停止才可以。不明白?
Message message = new Message();
message.what = 1;
handlerStop.sendMessage(message);
}
handler.postDelayed(update_thread, 1000); }
}; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); text_view = (TextView) findViewById(R.id.text_view);
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new StartClickListener());
end = (Button) findViewById(R.id.end);
end.setOnClickListener(new EndClickListener());
handler.post(update_thread);
} private class StartClickListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
// 将线程接口立刻送到线程队列中
handler.post(update_thread);
}
} private class EndClickListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
// 将接口从线程队列中移除
count = 0;
handler.removeCallbacks(update_thread);
}
} final Handler handlerStop = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
count = 0;
handler.removeCallbacks(update_thread);
break;
}
super.handleMessage(msg);
} };
}
.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <TextView
android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="200dip"
android:text="@string/hello_world"
tools:context=".MainActivity" /> <Button
android:id="@+id/start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="start" /> <Button
android:id="@+id/end"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="end" /> </LinearLayout>