BroadcastReceiver mBR;
private final SimpleDateFormat sdfnow = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private TextView sdfnow_for_tv;
@Override
public void onStart()
{
super.onStart();
mBR = new BroadcastReceiver() {
@Override
public void onReceive(Context ctx, Intent intent)
{
if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0) {
sdfnow_for_tv.setText(sdfnow.format(new Date()));
// Update your thing
}
}
};
registerReceiver(mBR, new IntentFilter(Intent.ACTION_TIME_TICK));
}
@Override
public void onStop()
{
super.onStop();
if (mBR!= null)
unregisterReceiver(mBR);
}
위는 BroadcastReceiver를 이용한 방법입니다. (1분마다 업데이트되는 방식)
아래는 Thread를 이용하여 매초마다 업데이트되는 방식입니다.
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
updateYOURthing();
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
///////////////////
private void updateYOURthing() {
now = System.currentTimeMillis();
date = new Date(now);
SimpleDateFormat sdfnow = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String strNow = sdfNow.format(date);
tv.setText(strNow);
}