zoukankan      html  css  js  c++  java
  • Android学习总结——实时显示系统时间

        我们都知道System.currentTimeMillis()可以获取系统当前的时间,这里要实时显示就可以开启一个线程,然后通过handler发消息,来实时的更新TextView上显示的系统时间。具体就是写一个线程,线程里面无限循环,每隔一秒发送一个消息,在主线程里面处理消息并更新时间。

       class TimeThread extends Thread {
            @Override
            public void run() {
                do {
                    try {
                        Thread.sleep(1000);
                        Message msg = new Message();
                        msg.what = 1;  //消息(一个整型值)
                        mHandler.sendMessage(msg);// 每隔1秒发送一个msg给mHandler
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } while (true);
            }
        }
    
        //在主线程里面处理消息并更新UI界面
        private Handler mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        long sysTime = System.currentTimeMillis();//获取系统时间
                        CharSequence sysTimeStr = DateFormat.format("hh:mm:ss", sysTime);//时间显示格式
                        time.setText(sysTimeStr); //更新时间
                        break;
                    default:
                        break;
    
                }
            }
        };

    然后在需要时启动线程就好,如下:

     protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          requestWindowFeature(Window.FEATURE_NO_TITLE);//去除标题栏
          setContentView(R.layout.activity_main);
          new TimeThread().start(); //启动新的线程
     }

         更多技术干货,欢迎关注我的公众号:ChaoYoung

              

  • 相关阅读:
    CVPR顶会热词统计
    @Annotation学习
    把一张表已有的数据对另一张表数据进行修改
    两张表数据不一致进行对比
    学习借鉴
    借鉴tcp
    借鉴tcp
    osi七层
    http学习
    Json学习
  • 原文地址:https://www.cnblogs.com/xch-yang/p/6065660.html
Copyright © 2011-2022 走看看