Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
74 views
in Technique[技术] by (71.8m points)

java - Android Thread for a timer

public class MainActivity extends Activity
{
int min, sec;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    min = 5;
    sec = 0;
    final TextView timer1 = (TextView) findViewById(R.id.timer1);
    timer1.setText(min + ":" + sec);
    Thread t = new Thread() {
        public void run() {
                sec-=1;
                if (sec<0) {
                    min-=1;
                    sec=59;
                }
                timer1.setText(min + ":" + sec);
                try
                {
                    sleep(1000);
                }
                catch (InterruptedException e)
                {}
            }
    };
    t.start();
}
}

This is a code for a Thread in Java but it doesn't work. Can you help me?

Its a Timer that counts down from 5 Minutes to 0:00.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your case you are using threads. So you cannot update ui from the thread other than the ui thread. SO you use runOnUithread. I would suggest you to use a countdown timer or a Handler.

1.CountDownTimer

http://developer.android.com/reference/android/os/CountDownTimer.html

Here's a link to another example. Suggest you to check the link for the count down timer.

Countdowntimer in minutes and seconds

Example:

 public class MainActivity extends Activity {

Button b; 
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = (TextView) findViewById(R.id.textView1);
    b= (Button) findViewById(R.id.button1);
    b.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            startTimer(200000); 
        }

    });
}
private void startTimer(long time){
    CountDownTimer counter = new CountDownTimer(30000, 1000){
        public void onTick(long millisUntilDone){

           Log.d("counter_label", "Counter text should be changed");
          tv.setText("You have " + millisUntilDone + "ms");                    
        }

        public void onFinish() {
            tv.setText("DONE!");

        }
    }.start();
}
 }

2.You can use a Handler

Example :

Handler m_handler;
Runnable m_handlerTask ; 
int timeleft=100;
m_handler = new Handler(); 
m_handlerTask = new Runnable() 
{ 
@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();     

3.Timer

Timer runs on a different thread. You should update ui on the ui thread. use runOnUiThread

Example :

  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 ); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...