您的位置:首页 > 移动开发 > Android开发

Android笔记:Android TextView实时显示系统时间

2016-12-30 16:25 591 查看
最近在写一个自定义锁屏的功能,用到时间的一个实时更新,通过SimpleDateFormat来获取系统的时间,但是存在一个问题,TextView的内容一旦设定好之后,就不会自动更新了,所以用一个线程,在线程里不断循环,线程每休眠1s,sendMessage给Handle,在handleMessage方法里更新UI线程即TextView的内容。

代码如下:

test.xml文件

<?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">

<TextView
android:textSize="40sp"
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/mytime"
android:layout_weight="1" />
</LinearLayout>


TestClass 文件(运行的Activity)

package com.dfwy.cxy.onecodetolock;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
* Created by cxy on 2016/12/30.
*/

public class TestClass extends Activity {
private TextView tv_time;
private static final int msgKey1 = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
tv_time = (TextView) findViewById(R.id.mytime);
new TimeThread().start();
}
public class TimeThread extends  Thread{
@Override
public void run() {
super.run();
do{
try {
Thread.sleep(1000);
Message msg = new Message();
msg.what = msgKey1;
mHandler.sendMessage(msg);

} catch (InterruptedException e) {
e.printStackTrace();
}
}while (true);
}
}
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case msgKey1:
long time = System.currentTimeMillis();
Date date = new Date(time);
SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 EEE");
tv_time.setText(format.format(date));
break;
default:
break;
}
}
};
}


效果展示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 线程