栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

计时器的Android线程

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

计时器的Android线程

在你的情况下,你正在使用线程。因此,你无法从ui线程以外的其他线程更新ui。所以你用

runOnUithread
。我建议你使用倒数计时器或处理程序。

1.CountDownTimer

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

这是另一个示例的链接。建议你检查倒计时计时器的链接。

倒数计时器,以分钟和秒为单位

例:

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

2.你可以使用 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.计时器

计时器在其他线程上运行。你应该在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 ); 


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/407697.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号