Three ways to use timers in Android _android

Source: Internet
Author: User
Tags dateformat

The example of this article for everyone to share the use of the timer in Android three ways, for your reference, the specific content as follows

Icon:

Because it is relatively simple, so just paste the code (take care to click the stop operation again), there is a global handler responsible for receiving the message update UI

The first method: Thread.Sleep (); Method

Runnable Runnable = new Runnable () {
    @Override public
  void Run () {while
   (true)
   { Mhandler.sendemptymessage (0);
 try {
   thread.sleep (1000);
  } catch (Interruptedexception e) {
    e.printstacktrace ();
     }
    }}
   };
New Thread (runnable). Start ();


The second method: Postdelay () method of Handler

Final Runnable Runnable = new Runnable () {
      @Override public
      void Run () {
        if (isStart2) {
          mhandler.sendemp Tymessage (0);
          Mhandler.postdelayed (this, 1000);
        }
      }
    ;
Mhandler.postdelayed (runnable, 1000);
    }

The third type: Timer and TimerTask

 Private Timer timer = new timer ();
  Private TimerTask TimerTask = new TimerTask () {
    @Override public
    void Run () {
      mhandler.sendemptymessage ( 0);
    }
  ;
 Timer.schedule (TimerTask, 1000, 1000);

In general, the third method is most convenient, not easy to make mistakes, the second is easy to forget to add the starting event.

Paste the complete code:

Layout file

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "xmlns:tools=" Http://schemas.android.com/tools "android:layout_width=" Match_parent "android:layout_height = "Match_parent" android:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_ Horizontal_margin "android:paddingright=" @dimen/activity_horizontal_margin "android:paddingtop=" @dimen/activity_
    Vertical_margin "tools:context=" com.brioal.timertest.MainActivity "> <textview android:id=" @+id/main_tv "
    Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_centerhorizontal= "true" android:layout_margintop= "100DP" android:text= "Hello world!"/> <linearlayout android:layout_width= "Ma Tch_parent "android:layout_height=" wrap_content "android:layout_below=" @id/main_tv "android:layout_margintop=" 100DP "android:gravity=" center "android:orientation= "vertical" > <button android:layout_width= "wrap_content" android:layout_height= "Wrap_cont" ENT "android:layout_gravity=" center "android:layout_margin=" 5DP "android:onclick=" Method1 "Android
      : text= "Method 1:thread" android:textallcaps= "false"/> <button android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "center" android:layout_margin= "5DP" Androi d:onclick= "Method2" android:text= "method 2:handler" android:textallcaps= "false"/> <button Android : layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "center" Androi D:layout_margin= "5DP" android:onclick= "Method3" android:text= "method 3:task" android:textallcaps= "false"/&gt
  ;

 </LinearLayout> </RelativeLayout>

mainactivity

Package com.brioal.timertest;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import android.support.v7.app.AppCompatActivity;
Import Android.view.View;

Import Android.widget.TextView;
Import Java.text.SimpleDateFormat;
Import Java.util.Timer;

Import Java.util.TimerTask;
  public class Mainactivity extends Appcompatactivity {private TextView mTv; Private Handler Mhandler = new Handler () {@Override public void Handlemessage (msg) {Super.handleme
      Ssage (msg);
      Displays the current time after receiving the message long = System.currenttimemillis ();
      SimpleDateFormat DateFormat = new SimpleDateFormat ("HH:mm:ss");
      String time = Dateformat.format (current);
    Mtv.settext (time);
  }
  };
  Private Timer timer = new timer ();
    Private TimerTask TimerTask = new TimerTask () {@Override public void run () {mhandler.sendemptymessage (0);
  }
  };
  Private Thread Thread1;
  Private Boolean isStart1 = false; Private Boolean IsSTart2 = false;


  Private Boolean isStart3 = false;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
  MTv = (TextView) Findviewbyid (R.ID.MAIN_TV); //thread method public void Method1 (view view) {Runnable Runnable = new Runnable () {@Override public V
          OID Run () {while (IsStart1) {mhandler.sendemptymessage (0);

          try {thread.sleep (1000);
          catch (Interruptedexception e) {e.printstacktrace ();
    }
        }

      }
    };
    if (isStart1) {isStart1 = false;
      else {IsStart1 = true;
      Thread1 = new Thread (runnable);
    Thread1.start (); } public void Method2 (view view) {final Runnable Runnable = new Runnable () {@Override public voi
          D Run () {if (IsStart2) {mhandler.sendemptymessage (0); Mhandler.postdelayed (This, 1000);
    }
      }
    };
    if (isStart2) {isStart2 = false;
      else {mhandler.postdelayed (runnable, 1000);
    IsStart2 = true;
      } public void Method3 (view view) {if (ISSTART3) {timer.cancel ();
    IsStart3 = false;
      else {timer.schedule (timertask, 1000, 1000);
    IsStart3 = true;
 }
  }
}

Finished, complete GitHub address: timertest

The above is the timer to use the entire content of the method, I hope to give you a reference, but also hope that we support the cloud habitat community.

Related Article

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.