我正在尝试创建一个显示当前时间的Android应用程序。我想用计时器更新我的活动的时间,但TextView没有更新,所以只有一次总是显示在屏幕上。下面是我的代码:
package com.example.androidtemp;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.example.androidtemp.R;
public class ActivityTime extends Activity
{
SimpleDateFormat sdf;
String time;
TextView tvTime;
String TAG = "States";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_time);
sdf = new SimpleDateFormat("HH:mm:ss");
time = sdf.format(new Date(System.currentTimeMillis()));
tvTime = (TextView) findViewById(R.id.tvTime);
Timer timer = new Timer();
TimerTask task = new TimerTask()
{
@Override
public void run()
{
// TODO Auto-generated method stub
timerMethod();
}
};
try
{
timer.schedule(task, 0, 1000);
}
catch (IllegalStateException e)
{
// TODO: handle exception
e.printStackTrace();
Log.e(TAG, "The Timer has been canceled, or if the task has been scheduled or canceled.");
}
}
protected void timerMethod()
{
// TODO Auto-generated method stub
this.runOnUiThread(changeTime);
}
private final Runnable changeTime = new Runnable()
{
public void run()
{
// TODO Auto-generated method stub
//Log.d(TAG, "Changing time.");
sdf.format(new Date(System.currentTimeMillis()));
tvTime.setText(time);
}
};
}有谁有解决这个问题的办法吗?
发布于 2012-12-10 03:21:32
如果你只是想显示时间,我建议你使用DigitalClock或TextClock (你可以在布局xml和布局/布局-v17中使用'include‘来使用不同的组件,这取决于操作系统的版本)。
如果你想有更多的控制,我建议你使用处理程序或ExecutorService而不是计时器。Java Timer vs ExecutorService?
如果您想按原样修复代码,只需修改变量'time‘的值;)
发布于 2012-12-10 02:56:36
使用处理程序,因为它可以访问应用程序的视图。应用程序的视图已经属于主线程,因此创建另一个线程来访问它们通常是不起作用的。如果我没有错,处理程序使用消息与主线程及其组件进行通信。在您有线程定义的地方使用以下代码:
Handler handler = new Handler();
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, 1000);并将其添加到您的runnable定义中
handler.postDelayed(runnable, 1000);最后一条语句删除添加新on时等待执行的runnable的所有实例。有点像清空队列。
https://stackoverflow.com/questions/13790547
复制相似问题