1. 运行效果
2. 设计知识
(1)线程(Thread)
(2)异步处理器(Handler)
3. 实现步骤
1、创建安卓应用Time
2、创建布局文件activity_time
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/tv_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="时间"
android:textSize="80dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始"
android:onClick="doStart"/>
<Button
android:id="@+id/two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止"
android:onClick="doStop"/>
</LinearLayout>
3、主界面TimeActivity
(1)代码
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
public class TimeActitity extends Activity {
private Thread thread;
private Handler handler;
private TextView textView;
private SimpleDateFormat sdf;
private Button button1;
private Button button2;
private boolean A;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time);
textView = findViewById(R.id.tv_time);
sdf=new SimpleDateFormat("hh:mm:ss");//定义时间格式
// 创建消息处理器,接收子线程发送的消息进行处理,更新主界面标签的内容
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what==0x0001){
textView.setText(sdf.format(new Date()));
}
}
};
}
//停止按钮
public void doStop(View v){
A=false;//将布尔值设为false线程循环终止
thread=null;//停止线程
}
//开始按钮
public void doStart(View v){
A=true;//开启循环
// 创建线程,定时发送消息
thread =new Thread(new Runnable() {
@Override
public void run() {
while (A){
handler.sendEmptyMessage(0x0001);//向主线程发送消息
try {
Thread.sleep(500);//线程睡眠0.5秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();//开始线程
}
//当程序销毁是停止线程
protected void onDestroy() {
super.onDestroy();
thread=null;
}
}
(2)内容讲解
开始线程与停止线程部分,用最简单的布尔值来开关循环,实现时间的停止与开始。当启动开始按钮时线程开始不断循环向主线程发送“0x0001”,当主线程收到对于消息时将我们获取的系统时间返回到文本框,循环发送达到