1 package com.example.table;
 2 
 3 import android.os.Bundle;
 4 import android.os.Handler;
 5 import android.os.Message;
 6 import android.widget.Button;
 7 import android.widget.TextView;
 8 
 9 import androidx.appcompat.app.AppCompatActivity;
10 
11 import java.text.SimpleDateFormat;
12 import java.util.Date;
13 
14 public class ShowTimeActivity extends AppCompatActivity {
15 
16     private  Thread thread;
17     private Handler handler;  //异步消息处理器
18     private TextView tvTime;
19     private SimpleDateFormat sdf;
20     private boolean runing;
21     private TextView Tv1;
22     private Button Btn1;
23 
24     @Override
25     protected void onCreate(Bundle savedInstanceState) {
26         super.onCreate(savedInstanceState);
27         setContentView(R.layout.activity_show_time);
28 
29         tvTime = findViewById(R.id.tv_1);
30         sdf = new SimpleDateFormat("hh:mm:ss");
31         tvTime.setText(sdf.format(new Date()));
32 
33         //创建消息处理器 接受子线程发送的消息  根据它做出处理,跟新主界面的值
34         handler = new Handler(){
35             @Override
36             public void handleMessage(Message msg) {
37                 super.handleMessage(msg);
38                 if(msg.what == 1){
39                     tvTime.setText(sdf.format(new Date()));
40                 }
41             }
42         };
43 
44         thread = new Thread(new Runnable() {
45             @Override
46             public void run() {
47                 while (true){
48                     //让线程  发送消息
49                     handler.sendEmptyMessage(1);
50                     //让线程  睡眠500毫秒
51                     try {
52                         Thread.sleep(500);
53                     } catch (InterruptedException e) {
54                         e.printStackTrace();
55                     }
56                 }
57             }
58         });
59         //启动线程
60         thread.start();
61     }
62 }