我是Android应用开发新手,今天写一个小程序,在UI每隔一秒刷新一次时间显示。
我启动了timer一秒执行一次任务,内容即setText为当前日期时间值;发现报错,才知道,关于修改UI的内容只能够在主线程中进行,timer启动的新的线程是无法刷新UI的。
所以,需要handler来处理,程序如下:
这是一个UI mainActivity:
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import net.tsz.afinal.FinalDb;
import net.tsz.afinal.http.AjaxParams;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.tcl.watch.ConfigData;
import com.tcl.watch.R;
import com.tcl.watch.bean.SensorBean;
import com.tcl.watch.data.Settings;
import com.tcl.watch.logic.DataService;
import com.tcl.watch.net.SensorTask;
public class MainActivity extends BaseActivity {
private static final String TAG = "MainActivity";
private TextView myTextView0, myTextView1;
private RelativeLayout myRelativeLayout;
private Context mContext;
private Timer mTimer = null;
private TimerTask mTimerTask = null;
private long delay = 1000; //1s
private long period = 1000;
private static String EncodeWeek[] = { "", "日", "一", "二", "三", "四", "五", "六" };
private static final int MAX_SAVE_DATE = 30;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
Settings.init(this);
myTextView0 = (TextView) findViewById(R.id.layoutTextView0); //这里显示时间
myTextView0.setText(getNowTime("hh : mm"));
myTextView1 = (TextView) findViewById(R.id.layoutTextView1);
myTextView1.setText(getNowTime("yyyy年MM月dd日") + " 星期" + EncodeWeek[getWeek()]);
myRelativeLayout = (RelativeLayout) findViewById(R.id.layoutScreen);
myRelativeLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, SubActivity.class);
MainActivity.this.startActivity(intent);
}
});
// new SensorTask().post(new AjaxParams());
// 查找超出时间界限的数据
FinalDb finalDb = FinalDb.create(mContext);
finalDb.deleteByWhere(SensorBean.class,
"DATE(dates) = DATE('now','-1 months','localtime')");
startTimer(); //这里启动定时器
}// 当前日期
public static String getNowTime(String dateformat) {
Date now = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);// 可以方便地修改日期格式
String currentDate = dateFormat.format(now);
return currentDate;
}
// 当前星期
public static int getWeek() {
Log.d(TAG, "lillian getWeek=" + Calendar.DAY_OF_WEEK);
return Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
}
/**
* 字符串的日期格式的计算
*/
public static int daysBetween(String oldDate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(oldDate));
long oldTime = cal.getTimeInMillis();
cal.setTime(new java.util.Date());
long newTime = cal.getTimeInMillis();
long between_days = (newTime - oldTime) / (1000 * 60 * 60 * 24);
return Integer.parseInt(String.valueOf(between_days));
}
private void startTimer() {
if (mTimer == null) {
mTimer = new Timer();
}
if (mTimerTask == null) {
mTimerTask = new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
timerHandler.sendMessage(message);
}
};
}
if (mTimer != null && mTimerTask != null)
mTimer.schedule(mTimerTask, delay, period);
}
//通过timerHandler更新UI时间显示
public Handler timerHandler = new Handler(){
public void handleMessage(Message msg) {switch (msg.what) {
case 1:
Log.d(TAG, "lillian updateNowtime");
updateNowTime();
break;
default:
break;
}
super.handleMessage(msg);
}
};
//update date and time on UI
private void updateNowTime() {
myTextView0.setText(getNowTime("hh : mm"));
myTextView1.setText(getNowTime("yyyy年MM月dd日") + " 星期" + EncodeWeek[getWeek()]);
}
@SuppressWarnings("unused")
private void stopTimer() {
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
if (mTimerTask != null) {
mTimerTask.cancel();
mTimerTask = null;
}
}
}