Timer works as in every frequent as assign the time. Timer
is used mainly in Slide show, Stop watch etc.
Here is the code to work with timer in android.
First need to declare timer variable as in android Java:
Timer t;
Create the object for Timer as:
t = new
Timer();
Code to use of time and assign
the frequency of time; You just need to call the timer;
public void StartTimer()
{
t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable()
{
@Override
public void run()
{
//Called each time when 1000 milliseconds
(1 second) (the period parameter)
//Your code should
be here
}
});
}
},
//Set how long before to start calling the
TimerTask (in milliseconds)
0,
//Set the amount of time between each
execution (in milliseconds)
5000);
}
If you want to stop the timer you need to call the below
method;
public void StopTimer()
{
t.cancel();
}
No comments:
Post a Comment