Android三种实现定时器的方法
方法一、使用Handler和Thread(线程)实现定时器
packagecom.xunfang.handerDemo; importandroid.app.Activity; importandroid.os.Bundle; importandroid.os.Handler; importandroid.os.Message; importandroid.widget.TextView; publicclassHanderDemoActivityextendsActivity{ TextViewtvShow; privateinti=0; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); tvShow=(TextView)findViewById(R.id.tv_show); newThread(newThreadShow()).start(); } //handler类接收数据 Handlerhandler=newHandler(){ publicvoidhandleMessage(Messagemsg){ if(msg.what==1){ tvShow.setText(Integer.toString(i++)); System.out.println("receive...."); } }; }; //线程类 classThreadShowimplementsRunnable{ @Override publicvoidrun(){ while(true){ try{ Thread.sleep(1000); Messagemsg=newMessage(); msg.what=1; handler.sendMessage(msg); System.out.println("send..."); }catch(Exceptione){ e.printStackTrace(); System.out.println("threaderror..."); } } } } }
方法二、使用Handler类自带的postDelyed实现定时器
packagecom.xunfang.handerDemo; importandroid.app.Activity; importandroid.os.Bundle; importandroid.os.Handler; importandroid.widget.TextView; publicclassHanderDemoActivityextendsActivity{ TextViewtvShow; privateinti=0; privateintTIME=1000; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); tvShow=(TextView)findViewById(R.id.tv_show); handler.postDelayed(runnable,TIME);//每隔1s执行 } Handlerhandler=newHandler(); Runnablerunnable=newRunnable(){ @Override publicvoidrun(){ //handler自带方法实现定时器 try{ handler.postDelayed(this,TIME); tvShow.setText(Integer.toString(i++)); System.out.println("do..."); }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); System.out.println("exception..."); } } }; }
方法三、使用Handler、Timer和TimerTask三个Android类实现定时器
packagecom.xunfang.handerDemo; importjava.util.Timer; importjava.util.TimerTask; importandroid.app.Activity; importandroid.os.Bundle; importandroid.os.Handler; importandroid.os.Message; importandroid.widget.TextView; publicclassHanderDemoActivityextendsActivity{ TextViewtvShow; privateinti=0; privateintTIME=1000; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); tvShow=(TextView)findViewById(R.id.tv_show); timer.schedule(task,1000,1000);//1s后执行task,经过1s再次执行 } Handlerhandler=newHandler(){ publicvoidhandleMessage(Messagemsg){ if(msg.what==1){ tvShow.setText(Integer.toString(i++)); } super.handleMessage(msg); }; }; Timertimer=newTimer(); TimerTasktask=newTimerTask(){ @Override publicvoidrun(){ //发送消息 Messagemessage=newMessage(); message.what=1; handler.sendMessage(message); } }; }