且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Android中显示当前时间并进行更新?

更新时间:2023-02-26 18:27:21

这种方法应该可以解决问题

Something like this should do the trick

final Handler someHandler = new Handler(getMainLooper());   
        someHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tvClock.setText(new SimpleDateFormat("HH:mm", Locale.US).format(new Date()));
                someHandler.postDelayed(this, 1000);
            }
        }, 10);

Activity 暂停并恢复时,您应该保留对处理程序和可运行对象的引用,以取消此操作.确保删除所有对处理程序的回调并将其在 onDestroy

You should keep a reference to the handler and the runnable to cancel this when the Activity goes to pause and resume when it resumes. Make sure you remove all callbacks to handler and set it to null in onDestroy