我正在尝试创建一个显示当前时间的 Android 应用程序。我想用 Timer 更新我的 Activity 时间,但 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);
}
};
}
有没有人有这个问题的解决方案?