Currently I am in process of developing my android application. My requirement is something like this.
I need to run a timer of 5mins and when timeout occurs I need to check certain things and take certain action. This need to be keep on running if the user starts the application.
In my knowledge I want to proceed like this
Create a service and start a timer in that service and do whatever needed when the timer expires. I will put one activity to interact with the service like start or stop.
I need suggestion for my approach and its pros and cons for this approach. To just run a timer do I need a service? If I run the repeated timer in a activity itself and if I press the back-button the activity will go background and will the timer also stop if I have started the timer in that activity?
I am sorry If I am not clear in my question. I have gone through the android application fundamentals and then thinking to ask this question. Please give me some idea.
There’s no need for a service. You can use a Timer and schedule a TimerTask. If the task needs to touch the UI, then you should create a Handler to which you can post a Runnable.
P.S. You asked about what happens if your activity goes to the background. The Timer will keep running unless you cancel either the task or the timer itself in
onPauseor one of the other lifecycle methods. Whichever one you do it in, you should start the timer task in the matching start-up lifecycle method. If you are not going to cancel the Timer itself, you should create it as a daemon thread.