【问题标题】:Is there anything wrong with this code where i am using Timer我使用 Timer 的这段代码有什么问题吗
【发布时间】:2014-07-20 07:03:11
【问题描述】:

我正在尝试获取最近的时间并将其显示在 TextView 中。并使用 Timer 和 timerTask 每秒获取当前时间,并使用 View 对象的 post 方法更新 UI。

下面是我的代码:

public class MainActivity extends Activity implements OnClickListener
{
  Button btnStart,btnStop;
  TextView txtRcntTime;
  Calendar c;
  private Timer timer;


  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initialize(); // method where i initialized all components

     c = Calendar.getInstance();

    btnStart.setOnClickListener(this);
    btnStop.setOnClickListener(this);
   }

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.buttonStart:
                start();
                break;
        case R.id.buttonStop:
                stop();
                 break;

    }
}

public void stop()
{
     if (timer!=null){
         timer.cancel();
         timer = null;
        }
  }

private void start() 
{
  if(timer != null)
    {  timer.cancel();  }

    TimerTask task = new TimerTask() {

        @Override
        public void run() {
            SimpleDateFormat df1 = new SimpleDateFormat("hh-mm-ss a");
            String formattedDate1 = df1.format(c.getTime());
            updateView(formattedDate1);
        }
    };
    timer = new Timer(true);
    timer.schedule(task, 0, 1000);
}

public void updateView(final String t) 
{        
    txtRcntTime.post(new Runnable() {
        String t2 = t;
        @Override
        public void run() 
            {   txtRcntTime.setText(t2);       }
    });
}
}

结果显示的是第一次点击按钮的时间,但没有更新。

【问题讨论】:

    标签: android timer


    【解决方案1】:

    问题:

    c = Calendar.getInstance();
    

    它实际上是在更新,但你只得到一个日历实例,因此在每 1 秒调用一次计时器任务时给你相同的时间。

    解决方案:

    通过每秒获取日历的实例来更新日历

    TimerTask task = new TimerTask() {
    
        @Override
        public void run() {
            SimpleDateFormat df1 = new SimpleDateFormat("hh-mm-ss a");
            Calendar cal = Calendar.getInstance();
            String formattedDate1 = df1.format(cal.getTime());
            updateView(formattedDate1);
        }
    };
    

    【讨论】:

    • 天啊!非常感谢。有时我认为我应该离开编程领域:-(
    猜你喜欢
    • 1970-01-01
    • 2022-06-10
    • 2015-04-25
    • 2018-09-09
    相关资源
    最近更新 更多