2015-04-05 58 views
0

我有一个定时器在一个线程中等待20秒前移动到一个新的活动,我在找什么是显示时间无论减少或在那个时候在一个textView中增加。 这里是我的代码:我想显示在一个线程定时器在textView(Live)

Thread timer = new Thread() { 
     public void run() { 
      try { 
       sleep(ie); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } finally { 

       Intent i = new Intent(Activity.this, Menu.class); 
       if (ie == 20000) { 
        startActivity(i); 
        overridePendingTransition(R.anim.pushin, R.anim.pushout); 
       } 
      } 
     } 
    }; 

    timer.start(); 

感谢您assisstance

回答

1

尝试,而不是一个线程一个CountDownTimer:

  CountDownTimer count = new CountDownTimer(20000, 1000) 
      { 

       int counter = 20; 

       @Override 
       public void onTick(long millisUntilFinished) 
       { 
        // TODO Auto-generated method stub 
        counter--; 
        textView.setText(String.valueOf(counter)); 

       } 

       @Override 
       public void onFinish() 
       { 

      startActivity(i); 
      overridePendingTransition(R.anim.pushin, R.anim.pushout); 
       } 
      }; 

      count.start(); 
+0

非常感谢你的解决方案很简单,而且正是我所需要的。 – AndroDev 2015-04-06 21:38:01

0

卡米洛Sacanamboy的答案是正确的。如果你想用线程做到这一点,一个解决方案可能是这样的:

final TextView status; //Get your textView here 

    Thread timer = new Thread() { 
     public void run() { 
      int time = 20000; 
      try { 
       while(time > 0){ 
        time -= 200; //Or whatever you might like 

        final int currentTime = time; 
        getActivity().runOnUiThread(new Runnable() { //Don't update Views on the Main Thread 
         @Override 
         public void run() { 
          status.setText("Time remaining: " + currentTime/1000 + " seconds"); 
         } 
        }); 
       } 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } finally { 

       Intent i = new Intent(Activity.this, Menu.class); 
       if (ie == 20000) { 
        startActivity(i); 
        overridePendingTransition(R.anim.pushin, R.anim.pushout); 
       } 
      } 
     } 
    }; 

    timer.start(); 
+0

当我们使用线程时,这也是一个很好的解决方案。非常感谢 – AndroDev 2015-04-06 21:38:32

相关问题