I want an alarm to trigger after 5 sec in android, but it's not working. It is triggering after 1 min instead 5 sec. Why?
@Override
public void onReceive(Context context, Intent intent) {
PowerManager powerManager=(PowerManager)context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock= powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"Power Manager");
wakeLock.acquire();
showNotification("Wake up. Alarm Triggered",context);
}
public void showNotification(String message ,Context context)
{
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
public void setAlarm(Context context)
{
Calendar calendar= Calendar.getInstance();
AlarmManager alarmManager=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent=new Intent(context, Alarm.class);
PendingIntent pendingIntent= PendingIntent.getBroadcast(context,0,intent,0);
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),5000,pendingIntent);
}
}
Quoting from the docs:
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).
If you want to do some action while your app is running (which is what I suppose from an interval of 5 seconds), use Handler:
Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.
In particular, postDelayed
or sendMessageDelayed
might be the right choice for your application (however, as you did not tell us about your primary objective, that's just guesswork).