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

时间:2011-06-19 05:59:00

标签: java android

我想实时显示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();
}

3 个答案:

答案 0 :(得分:5)

我会使用Runnable并将其延迟发布给Handler。

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);
    }
}

答案 1 :(得分:1)

您可以使用处理程序将更新发布到UI线程。查看更新计时器的最佳做法

http://developer.android.com/resources/articles/timed-ui-updates.html

答案 2 :(得分:1)

我建议不要设计自己的计时器来处理这个问题,我建议每隔一分钟使用广播接收列表发送此广告:[{3}}

如果您想了解如何执行此操作的示例代码,请与我们联系。