本文介绍了多个任务之间的Andr​​oid计时器更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾尝试多种方法有一个持续的更新计时器在多个活动的用户界面,并且似乎没有任何工作。我已经试过了AsyncTask的,处理程序和CountDownTimer。在code下面不执行第一Log.i声明....是否有更好的方式开始在主计时器(它必须从其它类调用)(这是唯一的持久化类)?

I have tried multiple ways to have a single persistent timer update the ui in multiple activities, and nothing seems to work. I have tried an AsyncTask, a Handler, and a CountDownTimer. The code below does not execute the first Log.i statement.... Is there a better way to start the timer (which must be called from another class) in Main (which is the only persistent class)?

 public static void MainLawTimer()
{
    MainActivity.lawTimer = new CountDownTimer(MainActivity.timeLeft, 1000) 
    {
           public void onTick(long millisUntilFinished) 
           {
               Log.i("aaa","Timer running. Time left: "+MainActivity.timeLeft);
              MainActivity.timeLeft--; 

              if(MainActivity.timeLeft<=0)
              {
                //do stuff
              }
              else
              {
                  //call method in another class                          
              }  
           }
public void onFinish() 
           {  }
    }.start();
}

要澄清我的问题:

当我运行code中的Log.i(AAA,定时跑)语句日志中从来没有表现出和CountDownTimer似乎永远不会启动。 MainLawTimer是从另一个类调用只(而不是同一类的。

When I run the code the Log.i("aaa","Timer running") statement is never shown in the log, and the CountDownTimer never seems to start. MainLawTimer is called from another class only (not within the same class.

推荐答案

有关CountDownTimer

For CountDownTimer

您可以使用处理程序

Handler m_handler;
Runnable m_handlerTask ; 
int timeleft=100;
m_handler = new Handler(); 
@Override
public void run() {
if(timeleft>=0)
{  
     // do stuff
     Log.i("timeleft",""+timeleft);
     timeleft--; 
}      
else
{
  m_handler.removeCallbacks(m_handlerTask); // cancel run
} 
  m_handler.postDelayed(m_handlerTask, 1000); 
 }
 };
 m_handlerTask.run();     

定时

  int timeleft=100;
  Timer _t = new Timer();  
  _t.scheduleAtFixedRate( new TimerTask() {
            @Override
            public void run() {

               runOnUiThread(new Runnable() //run on ui thread
                 {
                  public void run() 
                  { 
                    Log.i("timeleft",""+timeleft);  
                    //update ui

                  }
                 });
                 if(timeleft>==0)
                 { 
                 timeleft--; 
                 } 
                 else
                 {
                 _t.cancel();
                 }
            }
        }, 1000, 1000 ); 

您可以使用的AsyncTask 定时 CountDownTimer

这篇关于多个任务之间的Andr​​oid计时器更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 08:51