I’m developing a Service for Android, that must run in background, executing a function each 100 seconds. That’s the source code (example)
package com.example
import ....
public class Servizio extends Service {
public IBinder onBind(Intent intent) {
}
public void onCreate() {
}
public void onDestroy() {
//here put the code that stop the timer cycle
}
public void onStart(Intent intent, int startid) {
//i want to begin here the timercycle that each 100 s call myCycle()
}
public void myCycle() {
//code that i can't move on other class!!!
}
}
How I can do that? Now the service execute myCycle() just one time, beacause I put a calling in onStart().
Use a Timer with a TimerTask. To execute your method every 100 seconds, you can use the following in your
onStartmethod. Be aware that this method creates a new thread.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.