0

I have seen many questions like this in SO. but I didn't get the correct answer. I want an alarm to trigger at every 2 minutes after I press a button. So I set an alarm to do so and I set the interval to 3 seconds so that I can observe that my code is working. But the alarm doesn't work as I expected. It triggers at different time intervals like after 2 minutes and sometimes even more that that. And the average interval is more than 1 minute. I don't know what is wrong with this code.

This is my code

    Intent alarmIntent = new Intent(MyActivity.this, AlarmReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(MyActivity.this, 0, alarmIntent, 0);

    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    int interval = 3000;

    manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
            interval, pendingIntent);
    Log.v("xyz", "alarm started");

And I tried this also but it gives the same result`

    Intent alarmIntent = new Intent(MyActivity.this, AlarmReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(MyActivity.this, 0, alarmIntent, 0);

    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    int interval = 3000;

    manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+2000,
            interval, pendingIntent);
    Log.v("xyz", "alarm started");
slenderm4n
  • 292
  • 7
  • 15
  • 1
    `AlarmManager` does not support intervals that small. To get a small interval between tasks like that you need to probably use a `Handler` – Nick Friskel Jan 15 '17 at 20:21
  • 1
    You cannot set intervals of less than 1 minute anymore and `setRepeating()` is not accurate any more. See the [extensive documentation about change in the `AlarmManager` since Android 4.4 KitKat](https://developer.android.com/reference/android/app/AlarmManager.html). – David Wasser Jan 16 '17 at 11:18
  • @DavidWasser okay but when I use setInexactRepeating() it should do the work right ? – slenderm4n Jan 16 '17 at 11:36
  • 1
    `setInexactRepeating()` is not accurate, and you cannot set repeat times smaller than 1 minute. It works as you've described in your post. That's the way it works. – David Wasser Jan 16 '17 at 11:39
  • @DavidWasser actually my main purpose is to send my location details to a server hourly. so setInexactRepeating() can do the trick right? I do not want maximum accuracy. just need to send location coordinates at a average interval of 1 hour. – slenderm4n Jan 16 '17 at 11:46
  • Yes, should work. – David Wasser Jan 16 '17 at 11:51

0 Answers0