I am a newbie in android. I am developing an app in which a particular piece of code executes after every 5 seconds in background.To achieve this I am using a service with timer with a timer task in it. For sometime its working fine but after some indefinite my service is running but timer task stops automatically in android. Here is my code please help. Thanks in advance.
public void onStart(Intent intent, int startid) {
//this is the code for my onStart in service class
int delay = 1000; // delay for 1 sec.
final int period = 5000; // repeat 5 sec.
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
executeCode();
}, delay, period);
};
I guess you can attain this task better if you use CountDown Timer which has an inbuilt method which is called after time you have specified
Example
Edit
you can perform any function in OnTick method which will be called in every 1000 millisecond in above example
Learn more about it here
Generally TimerTask stops when device goes to sleep mode for long time. Try to use AlarmManager class for your requirement. AlarmManager uses lesser battery consumption too.
Here is an example, how to use AlarmManager
In my opinion, you should use AlarmManager with an IntentService to schedule repeating background tasks instead of Timer tasks. A Timer is unreliable and doesn't always work correctly within the Android Framework. Also, a Timer won't execute if the phone is asleep. You can have alarms wake up the phone to execute your code with AlarmManager.
See:
https://developer.android.com/reference/android/app/AlarmManager.html
http://mobile.tutsplus.com/tutorials/android/android-fundamentals-scheduling-recurring-tasks/
http://android-er.blogspot.in/2010/10/simple-example-of-alarm-service-using.html
In case of phone restart, you will need to trigger the alarm manager again. See this tutorial for exact instructions on how to do this:
http://www.androidenea.com/2009/09/starting-android-service-after-boot.html