A timer is primarily used to create a task to run on a regular basis.
Create an inherited task level. That is, the task runs every time.
Private class MyTask extends timertask{@Overridepublic void run () {message msg = new Message (); msg.what = 1;handler.sendme Ssage (msg);}}}
You can then use the
Timer timer = new timer (); Timer.schedule (new MyTask (), 1, 2000);
You can also use thread resume time-consuming operations directly. Here is also a timer and thread differences to use it.
Private class Mytread extends thread{int i = 0; @Overridepublic void Run () {while (true) {System.out.println (); i++:try{ Sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();}}}}
Hanler mechanism: Using Hanler.sendmessage (MSG) to pass message parameters in the new handler Handlemessage ()
method to accept the number of references. According to the msg.what operation inference, the corresponding operation.
Overall code:
Package Com.example.androidtest;import Java.util.timer;import Java.util.timertask;import android.os.Bundle;import Android.os.handler;import Android.os.message;import Android.annotation.suppresslint;import android.app.Activity; Import Android.view.menu;import Android.widget.textview;public class Mainactivity extends Activity {TextView show;@ Suppresslint ("Handlerleak") Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {switch ( Msg.what) {case 1:show.settext ("title:" + title); title ++;break;} Super.handlemessage (msg);}}; int title = 0; @Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); show = (TextView) Findviewbyid (r.id.show); Timer timer = new timer (); Timer.schedule (new MyTask (), 1, 2000);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} Private classMyTask extends timertask{@Overridepublic void run () {message msg = new Message (); msg.what = 1;handler.sendmessage (msg);}} }
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
Android handler mechanism and timer adoption