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

          

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM