Android Timer 定时器 更新UI,androidtimer,在使用Timer的时候经
分享于 点击 19119 次 点评:90
Android Timer 定时器 更新UI,androidtimer,在使用Timer的时候经
在使用Timer的时候经常遇到需要更新UI。因为Timer的执行事件是子线程,是无法直接操作UI的。这时候要使用到 Handler
Timer 主要属性 scheduleAtFixedRate(要执行的方法,开启后多久执行,间隔时间多久执行) ;
scheduleAtFixedRate(new MyTask(),0,1000);//我有一个MyTask类在0毫秒后执行,每间隔1秒执行一次zhxct=((TextView)findViewById(R.id.zhixingcount));//我窗体上的空间 class MyTask extends java.util.TimerTask{ @Override public void run() { // if(i==10) // this.cancel(); // TODO Auto-generated method stub i++; //System.out.println(i); //异步操作页面 Bundle bundle = new Bundle(); bundle.putInt("zxc", i);Message mag=new Message();mag.setData(bundle);han.sendMessage(mag); } }//更新UI private Handler han=new Handler(){ public void handleMessage(Message msg) { Bundle bundle= msg.getData(); int s= bundle.getInt("zxc"); zhxct.setText("执行次数:"+s); } };
用户点评