I was searching over the internet for last 2 days but I couldn't find any tutorial helpful. I have created a service and I am sending a notification in status bar when the service starts. I want that service to stop after showing the notification and start it again after 5 minutes. Please let me know if it is possible and provide me some helpful tutorials if you have any. I heard of TimerTask
and AlarmManager
and I tried to use them as well but I wasn't able to get the desired result.
EDIT: I need the service to be started every 5 minutes even if my application is not running.
Create a
Timer
object and give it aTimerTask
that performs the code you'd like to perform.The advantage of using a Timer object is that it can handle multiple TimerTask objects, each with their own timing, delay, etc. You can also start and stop the timers as long as you hold on to the Timer object by declaring it as a class variable or something.
You do not want to use a
TimerTask
since this depends on your application running continuously. AnAlarmManager
implementation makes it safe for your application to be killed between executions.Stating that you tried to use
AlarmManager
but did not get the desired result is not a helpful statement, in that it tells no one how to help you to get it right. It would be much more useful to express what happened.http://code4reference.com/2012/07/tutorial-on-android-alarmmanager/ contains what appears to be a useful tutorial on
AlarmManager
. Here are the salient points:1) Your alarm will cause an
Intent
to fire when it expires. It's up to you to decide what kind ofIntent
and how it should be implemented. The link I provided has a complete example based on a BroadcastReceiver.2) You can install your alarm with an example such as:
Below I have provided three files, MainActivity.java for start service, Second file MyService.java providing service for 5 Minute and Third is manifest file.
MainActivity.java
MyService.java
AndroidManifest.xml