public class MainActivity extends Activity{int min, sec;/** Called when the activity is first created. */@OverrIDepublic 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();}}
这是Java中的线程的代码,但它不起作用.你能帮助我吗?
它的计时器从5分钟到0点倒计时.
解决方法:
在您的情况下,您正在使用线程.所以你不能从ui线程以外的线程更新ui.所以你使用runOnUithread.我建议你使用倒数计时器或处理程序.
1.CountDownTimer
http://developer.android.com/reference/android/os/CountDownTimer.html
这是另一个例子的链接.建议您查看倒计时器的链接.
Countdowntimer in minutes and seconds
例:
public class MainActivity extends Activity {button b; TextVIEw tv;@OverrIDeprotected 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();} }
你可以使用Handler
示例:
Handler m_handler;Runnable m_handlerTask ; int timeleft=100;m_handler = new Handler(); m_handlerTask = new Runnable() { @OverrIDepublic 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在不同的线程上运行.你应该在ui线程上更新ui.使用runOnUiThread
示例:
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 );
总结 以上是内存溢出为你收集整理的java – 用于计时器的Android线程全部内容,希望文章能够帮你解决java – 用于计时器的Android线程所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)