【发布时间】:2016-12-21 21:47:28
【问题描述】:
我正在尝试在每天(23.59)结束时重复执行一项任务,因此我想使用 alarmmanager.setRepeating()。 在我的测试中,我提出了一些我认为会每秒重复一个任务的代码,它可以工作,但不是每秒重复一次任务,而是每分钟重复一次任务,我不知道为什么,因此我不确定我会能够让它为每一天工作。这是我的代码:
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);
}
}
我认为这是导致问题的行:
am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 1000, pi);
我以为 1000 以毫秒为单位?因此它应该是 1s ?
这是我在日志中收到的消息:
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
解决方案
Android 不允许您在不到一分钟的时间内重复一项任务,这就是为什么我的只是每分钟重复一次。为了设法让它在 23.59.59 每天重复,我使用了以下代码:
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);
【问题讨论】:
-
你的意思是 23.59?
-
哎呀,这就是我的意思
标签: android alarmmanager repeatingalarm