Android: AlarmManager 每天午夜重复执行一次任务

Android: AlarmManager recuring tasks once a day at midnight

我试图在每天 (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);

I thought the 1000 was in miliseconds ? it should therefore be 1s ?

是的。但是,在 Android 5.1 及更高版本上,you cannot schedule a repeating task that frequently。如果您尝试,它会四舍五入到一分钟。