1

I am using alarm manager (setInexactRepeating) but it fires events after an interval of 1 min.Is their any way I could set this interval to be 5 seconds.

    alarmIntent = new Intent(this, AlarmReceiver.class);

    pendingIntent = PendingIntent.getBroadcast(c, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //Alarm Interval
    int interval = 5000;

    //Firing alarm after an interval of 5 seconds
    manager.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), interval, pendingIntent);
Rahul
  • 189
  • 1
  • 13

3 Answers3

6

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.

David Heisnam
  • 2,463
  • 1
  • 21
  • 32
  • I want the task to be running even if the app is closed and activity is killed. – Rahul Aug 16 '15 at 10:15
  • You can use TimerTask class in order to execute or run tasks in subsequent time intervals. – Suhas K Aug 16 '15 at 10:15
  • @user3237960 Oh, then you could use the above code in a background service. – David Heisnam Aug 16 '15 at 10:16
  • If i use this code in background service , start the service and then kill the app immediately after it then system takes up some time to load the service again in the stack.I want it to be running throughout even if the app is killed without no jitters. – Rahul Aug 16 '15 at 10:27
  • `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.` I tried this on Android 5 device and set the `targetSdkVersion 18` but still acting the same so this part of the documentation is not true at all.. – mboy Oct 14 '16 at 00:09
  • @mboy See if the other answer that I just posted helps...if you didn't try it already. – David Heisnam Oct 15 '16 at 13:41
  • @DavidH The problem with handler is it stops executing when the device sleeps in Android 5.. Google is serious with saving battery life.. :) – mboy Oct 15 '16 at 20:45
  • @mboy Oh the answer that I'm talking about is not about handler. This one http://stackoverflow.com/a/40059721/2036537 – David Heisnam Oct 16 '16 at 04:49
0

There a many was of executing a background task at an interval. The simplest way is to create a new thread using the Runnable object. Look at the following code:

Runnable newThread = new Runnable() {
        @Override
        public void run() {
            while (true) {
                Log.d("Msg from BG Thread", "This message will be displayed every 5 seconds");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    };
    newThread.run();

Let me know if this solution works for you.

Vingtoft
  • 13,368
  • 23
  • 86
  • 135
  • I want the task to be running in background even if the app is killed.Alarm manager i believe is the way for doing this.if i use this code in Service that also is killed eventually by the android system. – Rahul Aug 16 '15 at 10:17
  • Ok. In the future try to clarify your needs in the question. This will avoid wasting everyones time :) – Vingtoft Aug 16 '15 at 10:21
  • I will be more cautious next time :) – Rahul Aug 16 '15 at 10:30
0

After a year, I think I'm just going to post another answer using AlarmManager. So here it is. You can set your targetSdkVersion as high as you want, and it'll work. No Services required!

public class AlarmReceiver extends BroadcastReceiver {

    int interval = 60000; // 1 minute

    @Override
    public void onReceive(Context context, Intent intent) {

            doYourThing();
            Intent i = new Intent(context, AlarmReceiver.class);
            AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
           // You can doYourThing() again after an interval
            am.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+interval, PendingIntent.getBroadcast(context, 1,  i, PendingIntent.FLAG_UPDATE_CURRENT));

        }
    }
}
David Heisnam
  • 2,463
  • 1
  • 21
  • 32