package com.example.scm;
import android.annotation.SuppressLint;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.os.SystemClock.sleep;
public class CalendarTime {
@SuppressLint("SimpleDateFormat")
public static SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static Date date;
public static String dayandtime=simpleDateFormat.format(date);
public static TextView TitleTimeText;
//使用前请绑定控件
//TitleTimeText = findViewById(R.id.title_2_time);
public CalendarTime() {
new Thread(() -> {
while (true) {
CalendarTime.date=new Date(System.currentTimeMillis());
dayandtime=simpleDateFormat.format(date);
//1 TitleTimeText.setText(CalendarTime.dayandtime);
sleep(1000);
}
}).start();
}
}
思路:1个秒级更新线程,获取和显示每秒一次,达到秒级更新。
2.使用比较灵活,可以直接主程序将线程一块copy过去就行,然后绑定控件,写控件都在线程完成。
3.子线程中更新UI是不安全 的,所以待改为线程间通信,让UI线程去处理界面UI的更新。当然,android studio中它还是可以运行的,但是会报线程不安全异常。应该改为:
package com.example.scm;
import android.annotation.SuppressLint;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.os.SystemClock.sleep;
public class CalendarTime {
@SuppressLint("SimpleDateFormat")
public static SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static Date date;
public static String dayandtime=simpleDateFormat.format(date);
//public static TextView TitleTimeText;
//使用前请绑定控件
//TitleTimeText = findViewById(R.id.title_2_time);
public CalendarTime() {
new Thread(() -> {
while (true) {
CalendarTime.date=new Date(System.currentTimeMillis());
dayandtime=simpleDateFormat.format(date);
Message msg=new Message();
msg.arg1=0x1000;
//msg.obj=dayandtime;
if(MainActivity.handle!=null)
MainActivity.handle.sendMessage(msg);
//1 TitleTimeText.setText(CalendarTime.dayandtime);
sleep(1000);
}
}).start();
}
}
主mainactivity中收:
CalendarTime calendartime=new CalendarTime();//启动日历时间对象像线程
Handler handle=new Handler(){
public void handleMessage(Message msg){
if(msg.arg1==0x1000)
textview.setText(CalendarTime.dayandtime);//接收设置数据
}
}
如果handle里面的数据太多,可以标注为弱参数,让GC及时处理。
这样就没有隐患了。