gpt4 book ai didi

java - 在 Android 中按秒更新时间和日期

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:32:43 24 4
gpt4 key购买 nike

我想在 TextView 中实时显示时间和日期(按分钟更新)。目前,我有这个。考虑到内存使用和 Android 最佳实践,这是最好的方法吗? (注意:DateFormatjava.text.DateFormat)

private Thread dtThread;

public void onCreate(Bundle savedInstanceState) {
...
getDateAndTime();
}

private void getDateAndTime() {
dtThread = new Thread( new Runnable() {

@Override
public void run() {
Log.d(TAG, "D/T thread started");
while (!Thread.currentThread().isInterrupted()) {
try {
update();
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.d(TAG, "D/T thread interrupted");
}
}
}

public void update() {
runOnUiThread( new Runnable() {

@Override
public void run() {
Date d = new Date();
String time = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(d);
String date = DateFormat.getDateInstance(DateFormat.LONG).format(d);

TextView timeView = (TextView) findViewById(R.id.textStartTime);
TextView dateView = (TextView) findViewById(R.id.textStartDate);
timeView.setText(time);
dateView.setText(date);
}

});
}

});

dtThread.start();
}

protected void onPause() {
super.onPause();
dtThread.interrupt();
dtThread = null;
}

protected void onResume() {
super.onResume();
getDateAndTime();
}

最佳答案

我会使用 Runnable 并将其延迟发送到处理程序。

public class ClockActivity extends Activity {

private SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");

private TextView mClock;
private boolean mActive;
private final Handler mHandler;

private final Runnable mRunnable = new Runnable() {
public void run() {
if (mActive) {
if (mClock != null) {
mClock.setText(getTime());
}
mHandler.postDelayed(mRunnable, 1000);
}
}
};

public ClockActivity() {
mHandler = new Handler();
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mClock = (TextView) findViewById(R.id.clock_textview);
startClock();
}

private String getTime() {
return sdf.format(new Date(System.currentTimeMillis()));
}

private void startClock() {
mActive = true;
mHandler.post(mRunnable);
}
}

关于java - 在 Android 中按秒更新时间和日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6400846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com