显示效果:
Android使用线程更新系统时间到TextView
1.添加TextView控件
2.获取控件
3.启动线程
@Override
protected void onStart() {
super.onStart();
Thread t = getThread(tv);
t.start();
System.out.println("线程已启动===>线程名:"+t.getName()+" 线程ID: "+t.getId()+
" 线程状态: "+t.getState()+ " Alive: "+
t.isAlive()+" Daemon: "+t.isDaemon());
}
4.在线程中更新UI
@NonNull
private Thread getThread(TextView tv) {
Thread t = new Thread(() -> {
while (true){
try {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
tv.setText(LocalDateTime.now().format(fmt));
Thread.sleep(1);
} catch (InterruptedException e) {
System.out.println("===>thread catch error: "+e.getMessage());
break;
}
}
});
t.setDaemon(true);
t.setName("_thread_update_time_to_ui");
return t;
}
源码地址:
https://github.com/tonyimax/UpdateTimeByThread.git