2015-09-25 92 views
0

我是新来的android,并且一直在阅读有关工作线程和不阻塞UI线程的内容。我正在玩一个简单的计时器应用程序,该应用程序启动一个线程,在创建活动时每秒更新一次文本视图。所以我的问题是,现在最好的办法是做什么。下面的两个例子都有效,但是有更好的(更有效率/更多的Android)方式吗?性能 - 从计时器线程更新UI而不会阻塞UI线程

final Handler handler = new Handler(); 

    handler.postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      seconds++; 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        secondsTextView.setText(seconds); 
       } 
      }); 
      handler.postDelayed(this, 1000); 
     } 
    }, 1000); 

new Thread(){ 
     @Override 
     public void run(){ 
      try{ 
       while(!isInterrupted()){ 
        Thread.sleep(1000); 
        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          seconds++; 
          secondsTextView.setText(seconds); 
         } 
        }); 
       } 
      }catch(Exception e){ 
       Log.e("Activity1", e.toString()); 
      } 
     } 
    }.start(); 
+0

虽然你的两个例子都不是那么好。 – Elltz

回答

3

的更有效的方法是:

timeOnTextView.postDelayed(new Runnable() { 
     @Override 
     public void run() { 
     seconds++; 
     timeOnTextView.postDelayed(this, 1000); 
     } 
    }, 1000); 

Runnable传递给postDelayed()run()调用主应用程序线程,所以你不需要使用runOnUiThread()

由于postDelayed()实施于View,您不需要Handler