AlarmManager在错误的时间运行

时间:2017-05-31 12:38:49

标签: android timer alarmmanager

我试图让AlarmManager每隔3分钟运行一次,但它运行的时间错误且不同,时间以秒为单位,其他时间不运行。我试图在Android 7.0和另一个6.0设备上测试并且两者都运行错误,我看到以下注释但无法修复。

Alarm Manager Example AlarmManager fires alarms at wrong time Android AlarmManager fire at wrong time

以下代码:

long repeatTime = 180000;

        AlarmManager processTimer = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intentAlarm = new Intent(context, TimerProcessReceiver.class);
        PendingIntent pendingIntentAlarm = PendingIntent.getBroadcast(context, 0,
                intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT);

        if (android.os.Build.VERSION.SDK_INT < 19) {
            processTimer.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
                    repeatTime, pendingIntentAlarm);
        } else {
            processTimer.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() +
                    repeatTime, pendingIntentAlarm);
        }

仍有问题,我已按上述方式更新。更新为@ Vyacheslav的回复

long repeatTime = 180000 + System.currentTimeMillis();
    AlarmManager processTimer = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intentAlarm = new Intent(context, ProcessReceiver.class);
    PendingIntent pendingIntentAlarm = PendingIntent.getBroadcast(context, 0,
            intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT);

    int currentapiVersion = Build.VERSION.SDK_INT;

    if (Build.VERSION.SDK_INT >= 23) {
        processTimer.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
                repeatTime, pendingIntentAlarm);

    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            processTimer.setExact(AlarmManager.RTC_WAKEUP,
                    repeatTime, pendingIntentAlarm);

    } else if (currentapiVersion < Build.VERSION_CODES.KITKAT) {

        processTimer.set(AlarmManager.RTC_WAKEUP,  repeatTime,
                pendingIntentAlarm);

    }

如果我使用具有0和1的PendingIntent的两个同时定时器(但是添加这些PendingIntent的结构与上面的代码相同)但是具有相同的运行时间3分钟。两者都在几秒钟内随机执行错误的方式。

1 个答案:

答案 0 :(得分:0)

请改用setExactAndAllowWhileIdle(int type, long triggerAtMillis, PendingIntent operation)。它有助于唤醒您的设备。

修改

 int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion < android.os.Build.VERSION_CODES.KITKAT){
            am.set(AlarmManager.RTC_WAKEUP, nexttime, pi);
        } else {
            if (currentapiVersion < android.os.Build.VERSION_CODES.M) {
                am.setExact(AlarmManager.RTC_WAKEUP, nexttime, pi);
            } else {
                    am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nexttime, pi);
            }
        }