代码中使用handler作为一个定时器,每隔0.5秒发送一次消息,在handleMessage中处理消息,等待0.5秒再次发送一更新显示的消息。
如上一直循环。在内部类MyHandler中使用MainActivity的弱引用,防止内存泄露。
package com.wind.digitclock;
import java.lang.ref.WeakReference;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private Handler mHandler;
private static final int MSG_UPDATE_CURRENT_TIME = 1;
private TextView tv_time;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_time = (TextView)this.findViewById(R.id.time);
mHandler = new MyHandler(this);
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_CURRENT_TIME, 500);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private static class MyHandler extends Handler {
private WeakReference<MainActivity> mActivity;
public MyHandler(MainActivity activity) {
mActivity = new WeakReference<MainActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
MainActivity activity = mActivity.get();
switch (msg.what) {
case MSG_UPDATE_CURRENT_TIME:
activity.updateCurrentTime();
sendEmptyMessageDelayed(MSG_UPDATE_CURRENT_TIME, 500);
break;
default:
break;
}
}
}
private void updateCurrentTime() {
/*SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date curDate = new Date(System.currentTimeMillis());
String time = simpleDateFormat.format(curDate);
tv_time.setText(time);*/
Date now = new Date();
DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
DateFormat.MEDIUM, Locale.CHINA);
String time = format.format(now);
tv_time.setText(time);
}
}