代碼中使用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
mActivity;
public MyHandler(MainActivity activity) {
mActivity = new WeakReference(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);
}
}