2012-12-09 15 views
2

我正尝试创建一个显示当前时间的Android应用程序。我想用定时器更新我的Activity的时间,但TextView没有更新,所以只有一次总是在屏幕上。这里是我的代码:无法在我的Android应用程序中使用Timer更新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); 
     } 
    }; 
} 

有没有人有这个问题的解决方案?

回答

0

如果您只是想显示时间,我会推荐您使用DigitalClock或TextClock(您可以在布局xml和layout/v17​​中使用'include'来使用不同的组件,具体取决于操作系统版本)。

如果你想有更多的控制,我会建议你使用处理程序或ExecutorService而不是定时器。 Java Timer vs ExecutorService?

如果你想修复你的代码,因为它是,刚刚修改的变量“时间”的价值;)

+0

非常感谢!我只是没有看到我没有修改'时间'值:) –

0

使用处理程序,因为它可以访问应用程序的视图。您的应用程序的视图已属于主线程,因此创建另一个线程来访问它们通常不起作用。如果没有错,处理程序使用消息与主线程及其组件进行通信。使用这个,你有你的线程定义来代替:

Handler handler = new Handler(); 
handler.removeCallbacks(runnable); 
handler.postDelayed(runnable, 1000); 

,并添加到您可运行的定义

handler.postDelayed(runnable, 1000); 

这最后的语句删除可运行等待执行的任何实例时,一个新的添加。有点像清理队列。