Create a private Handler
variable in your Activity
private Handler mHandler = new Handler();
Then create a Runnable
private Runnable myTask = new Runnable() {
public void run() {
doMyThing();
mHandler.postDelayed(this, 5000); // Running this thread again after 5000 milliseconds }
};
To start running the task every 5 seconds
mHandler.postDelayed(myTask, 0);
Then to stop running the task
mHandler.removeCallbacks(myTask);
This way myTask will be executed every 5 seconds without having to keep a loop running constantly.
EDIT:
You cannot have exact intervals with repeating alarms starting from API level 19. If you want to use AlarmManager, and your application's targetSdkVersion is 19 or higher, use the setExact()
method as described below.
public void setExact (int type, long triggerAtMillis, PendingIntent operation)
Added in API level 19
Schedule an alarm to be delivered precisely at the stated time.
This method is like set(int, long, PendingIntent), but does not permit the OS to adjust the delivery time. The alarm will be delivered as nearly as possible to the requested trigger time.
I think that waking up the CPU in 5 second intervals indefinitely is just too expensive in terms of battery usage.
See this
Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.
And this
Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.
The last quote means that the OS will always change the interval in repeating alarms, in API level 19 and above. So you won't be able to get exactly 5 seconds with repeating alarms in newer platforms.
So the best solution is to use setExact()
and reschedule every time your code is executed.
Or if you want to use repeating alarm with exact interval, use setRepeating()
while setting targetSdkVersion
below 19 like in the quoted text above.