Android显示实时时间

android 实时显示系统时间

      我们知道,用System.currentTimeMillis()可以获取系统当前的时间,我们可以开启一个线程,然后通过handler发消息,来实时的更新TextView上显示的系统时间。

  我们开启一个线程,线程每隔一秒发送一次消息,我们在消息中更新TextView上显示的时间就ok了。

  首先我们在布局文件中放一个TextView用来显示时间,如下所示:

  

复制代码
<?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:background="@android:color/white">

<TextView

  android:id="@+id/mytime"

  android:layout_width="match_parent"

  android:layout_height="match_parent"

  android:gravity="center"

  android:textColor="@android:color/black"

  android:textSize="36sp"/>

</LinearLayout>

复制代码

  主要思想是写一个线程,线程里面无限循环,每隔一秒发送一个消息,在主线程里面处理消息并更新时间

  整个Activity的代码:

复制代码
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.text.format.DateFormat;import android.widget.TextView;

public class TestActivity extends Activity {

    private TextView tvTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tvTime = (TextView) findViewById(R.id.mytime);
        new TimeThread().start(); //启动新的线程
    }

    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); tvTime.setText(sysTimeStr); //更新时间
       break;
        default:
          break;
} } }; }
 
原文地址:https://www.cnblogs.com/fengjingfei/p/12763625.html