Android handler mechanism and use of timer

Source: Internet
Author: User

A timer is primarily used to create tasks that are performed at intervals.

Create task classes that inherit tasks, that is, the tasks that are performed at each time.

Private class MyTask extends timertask{@Overridepublic void run () {message msg = new Message (); msg.what = 1;handler.sendme Ssage (msg);}}}
You can use it later.

Timer timer = new timer (); Timer.schedule (new MyTask (), 1, 2000);


Hanler mechanism: Using Hanler.sendmessage (msg) to pass the message parameter in the new handler Handlemessage ()

Method accepts parameters. According to msg.what operation judgment, carry on 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);}} }





Android handler mechanism and use of timer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.