How To Make A Simple Timer Without New Class In Android?
Solution 1:
Use a Timer with a TimerTask. To execute your method every 100 seconds, you can use the following in your onStart
method. Be aware that this method creates a new thread.
new Timer().schedule(new TimerTask() {
@Override
public void run() {
myCycle();
}
}, 0, 100000);
Alternatively, use an android.os.Handler as described in this article: Updating the UI from a Timer. It is better than a Timer because it runs in the main thread, avoiding the overhead of a second thread.
privateHandlerhandler=newHandler();
Runnabletask=newRunnable() {
@Overridepublicvoidrun() {
myCycle();
handler.postDelayed(this, 100000);
}
};
handler.removeCallbacks(task);
handler.post(task);
Solution 2:
I usually do this, if I understood correctly you wanted the myCycle to execute every 100 secs.
TimermyTimer=newTimer();
myTimer.schedule(newTimerTask() {
@Overridepublicvoidrun() {
myCycle();
}
}, 0,100000);
Solution 3:
When I had this issue, where I call out to a webservice on a periodic basis this was my solution:
publicclassMyServiceextendsService {
privateHandlermHandler=newHandler();
publicstaticfinalintONE_MINUTE=60000;
privateRunnableperiodicTask=newRunnable() {
publicvoidrun() {
mHandler.postDelayed(periodicTask, 100 * ONE_MINUTE);
token = retrieveToken();
callWebService(token);
}
};
I call the postDelayed early so that the delay from the webservice call doesn't cause the timing to shift.
The two functions are actually in the MyService
class.
UPDATE:
You can pass a Runnable to postDelayed as shown here:
http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long)
public final boolean postDelayed (Runnable r, long delayMillis)
Since: API Level 1 Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the thread to which this handler is attached.
Also, my code won't compile due to missing functions, this is shown as an example of what the OP can do.
Post a Comment for "How To Make A Simple Timer Without New Class In Android?"