//时间与本机时间同步
package dc.cn.common;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeThread extends Thread {
public TextView tvDate;
private int msgKey1 = 22;
public TimeThread(TextView tvDate) {
this.tvDate = tvDate;
}
@Override
public void run() {
do {
try {
Message msg = new Message();
msg.what = msgKey1;
mHandler.sendMessage(msg);
Thread.sleep(1000);//暂停1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (true);
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 22:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//日期格式化
String date = sdf.format(new Date());
tvDate.setText(date);
break;
default:
break;
}
}
};
}
调用方法
TimeThread timeThread = new TimeThread(tvDate);//tvDate 是显示时间的控件TextView
timeThread.start();
网友评论