永远运行线程+在android中更新UI

时间:2013-03-21 22:46:41

标签: android multithreading

假设我有一个TextView,我想从应用程序的开头一直连续地用随机数更新它的文本,直到它终止。

执行此类任务的方法是什么?它必须定时吗? (即在一秒钟内更新一次等)。使用while(true)的语句不能使用,因为android中只有一个UI线程,这样的语句会永久阻止它。

编辑:感谢您快速准确的回答。在看到答案并稍微思考之后,我想出了一个实现这一目标的棘手方法。这种技术有什么缺点吗?

    TextView tv;
Handler myHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);     
    tv=(TextView) findViewById(R.id.textView1);     
    myHandler=new Handler();
    myHandler.post(new Nani());
}

    private class Nani implements Runnable{
    int i=0;
    @Override
    public void run() {
        tv.setText(Integer.toString(i));
        myHandler.post(this);
        i++;
    }       
}

简单地说,Runnable排队了..

4 个答案:

答案 0 :(得分:2)

在不了解您正在做什么的更多信息(例如何时或为何)时,您需要使用HandlerpostAtTime()This part of the Docs更多地讨论了如何根据您的需要处理这些事情

答案 1 :(得分:1)

这可以通过使用Looper类来实现:http://developer.android.com/reference/android/os/Looper.html

可以在此处找到使用此功能的好教程:http://pierrchen.blogspot.dk/2011/10/thread-looper-and-handler.html

答案 2 :(得分:0)

我认为最好的方法是使用带定时器的Handler。但要确保在参加一项或其他活动时不得杀死或终止跑步者

e.g:

   private void timer() {
      mRunnable = new HandlerManger();
      mHandler = new Handler();
      mHandler.postDelayed(mRunnable, 1000*10);
   }

可运行的

 private class HandlerManger implements Runnable {

      @Override
      public void run() {
        // your business logic method here;
      }
   }

活动

 private Handler mHandler;
   private Runnable mRunnable;

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

答案 3 :(得分:0)

这种自动重启CountDownTimer的示例方法可以。虽然这可能不是最好的方法,但它会起作用

     public class CountDown extends Activity {

      TextView tv; 

       /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

       tv = new TextView(this);
       this.setContentView(tv);

      //5000 is the starting number (in milliseconds)
      //1000 is the number to count down each time (in milliseconds)
      MyCount counter = new MyCount(5000,1000);

      counter.start();

         }

         public class MyCount extends CountDownTimer{

      public MyCount(long millisInFuture, long countDownInterval) {
         super(millisInFuture, countDownInterval);
         }

          @Override
         public void onFinish() {
         this.start();
         }

       @Override
        public void onTick(long millisUntilFinished) {
       tv.setText("your values here");

      }

     }
    }