问题
I am trying to make a task repeat at the end of each day (23.59) to do so I would like to use alarmmanager.setRepeating(). In my test i have come up with a bit of code that i thought would repeat a task every second, it works but instead of being everyseconds it repeats the tasks every minute, I am not sure why and therefore I am not sure that I will be able to make it work for every day. Here is my code:
public class RecurringTasks extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
// add calculation logic here
Toast.makeText(context, "happening !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
}
public void setRecurringTasks(Context context)
{
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, RecurringTasks.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 1000, pi);
}
public void cancelRecurringTasks(Context context)
{
Intent intent = new Intent(context, RecurringTasks.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
This is the line that is causing problem i think:
am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 1000, pi);
I thought the 1000 was in miliseconds ? it should therefore be 1s ?
Here is the message I get in my logs:
D/DEBUG: im repeating
E/EGL_emulation: tid 3322: eglSurfaceAttrib(1165): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9773e540, error=EGL_BAD_MATCH
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb2c768a0
SOLUTION
Android will not allow you to repeat a task in less then one minute this is why mine was only repeating every minute. To manage to make it repeat every day at 23.59.59 I used the following code:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23); // For 1 PM or 2 PM
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, RecurringTasks.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
回答1:
I thought the 1000 was in miliseconds ? it should therefore be 1s ?
It is. However, on Android 5.1 and higher, you cannot schedule a repeating task that frequently. If you try, it will be rounded up to a minute.
来源:https://stackoverflow.com/questions/41272442/android-alarmmanager-recuring-tasks-once-a-day-at-midnight