定时器的使用
方式一 , handler.postDelayed 定时
timerCount = Integer.parseInt(timer_tv.getText().toString()); // 页面上10秒 倒数 handler = new Handler(); // 开启 定时器 handler.postDelayed(runnable, 1000); // 1秒发送一次
---------------------------------------------------- Runnable runnable = new Runnable() { private boolean isStop = false; // 停止标志位 @Override public void run() {
//------------业务处理 Toast.makeText(JpushNotifyordersActivity.this, "定时器运行中", 300) .show(); timerCount--; if (timerCount == 0) { timerCount = 10; isStop = true; // 停止发送 // handler.removeCallbacks(runnable); //停止的方法// 请求网络 finish(); } timer_tv.setText("" + timerCount); if (!isStop) { // handler.postDelayed(this, 1000); //重复发送 } } };
方式二 :
Timer 和 TimerTask 定时
handler = new Handler() { public void handleMessage(Message msg) { adViewPager.setCurrentItem(msg.what); super.handleMessage(msg); } }; bannerTimer = new Timer(); //*********以上是初始化**************** //启动banner自动轮播 public void bannerStartPlay(){ if (bannerTimer != null) { if (bannerTimerTask != null) bannerTimerTask.cancel(); //加上 bannerTimerTask = new BannerTimerTask(); bannerTimer.schedule(bannerTimerTask, 5000, 5000);//5秒后执行,每隔5秒执行一次 } } //暂停banner自动轮播 public void bannerStopPlay(){ if (bannerTimerTask != null) bannerTimerTask.cancel(); } class BannerTimerTask extends TimerTask { @Override public void run() { // TODO Auto-generated method stub System.out.println("banner playing"); Message msg = new Message(); if (bannerViewList.size() <= 1) return; int currentIndex = adViewPager.getCurrentItem(); if (currentIndex == bannerViewList.size() - 1) msg.what = 0; else msg.what = currentIndex + 1; handler.sendMessage(msg); } }