我是android新手。我正在创建一个竞赛应用,其中我有ListView
,其中包含事件的状态。是否开始。当当前时间超过事件开始时间时,应自动更新。
我正在使用AsyncTask
,但不是很准确。
@Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater scheduleInflater = LayoutInflater.from(getContext());
final Holder h;
if(view == null){
view = scheduleInflater.inflate(R.layout.custom_list , parent , false);
h = new Holder();
h.eventName=(TextView) view.findViewById(R.id.eventNameCustomList);
h.eventStatus=(TextView) view.findViewById(R.id.eventStatus);
h.leftTime = (TextView) view.findViewById(R.id.leftTime);
h.rightTime= (TextView) view.findViewById(R.id.rightTime);
view.setTag(h);
}else{
h = (Holder) view.getTag();
}
final data d = getItem(position);
h.eventName.setText(d.getEventName());
Date startDate= d.getStartDate();
Date endDate = d.getEndDate();
long stTime = startDate.getTime();
long now = System.currentTimeMillis();
if(now >= stTime) {h.eventStatus.setText(Html.fromHtml(startedText));}
else {h.eventStatus.setText(Html.fromHtml(upcomingText));}
h.eventStatus.setTag(String.valueOf(position)); // Setting Tag of each TextView to its position to avoid incorrect ayncTask update
new go(h.eventStatus).execute(d.getStartDate()); // starting a thread to update the Text view
return view;
}
public class go extends AsyncTask<Date, Void , Boolean> {
String path;
TextView status;
public go(TextView eventStatus){
this.status=eventStatus;
this.path=eventStatus.getTag().toString();
}
@Override
protected Boolean doInBackground(Date... params) {
Date startDate = params[0];
while(true){
long curTime = System.currentTimeMillis();
long startTime = startDate.getTime();
if (curTime >= startTime) {return true;}
}
}
@Override
protected void onPostExecute(Boolean b) {
if(!status.getTag().toString().equals(path)) return;
if(b!=null && status!=null){
if(b==true) status.setText(Html.fromHtml(startedText));
else status.setText(Html.fromHtml(upcomingText));
}else{
status.setText(Html.fromHtml(upcomingText));
}
}
}
static class Holder{
TextView eventName , eventStatus;
TextView leftTime, rightTime;
}
如何在当前时间超过开始时间时更新TextView
。请帮助并建议更好的解决方案。
答案 0 :(得分:0)
你的应用程序变慢的原因是你在while(true)
内不必要地运行检查,这会占用太多资源并使整个设备变慢。
更好的方法是在延迟一段时间后执行更新操作,即时机到来。
请按照以下步骤操作:
使用android.os.Handler
执行延迟代码。如下所示(在事件开始之后用毫秒替换timeInMillis
):
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
}
}, timeInMillis);
答案 1 :(得分:0)
final Handler handler = new Handler();
Timer timer = new Timer(false);
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
// My check to do every second
}
});
}
};
timer.schedule(timerTask, 1000); // 1000 = 1 second.