簡體   English   中英

AlarmManager在錯誤的時間運行

[英]AlarmManager running at the wrong time

我試圖讓AlarmManager每隔3分鍾運行一次,但它運行的時間錯誤且不同,時間以秒為單位,其他時間不運行。 我試圖在Android 7.0和另一個6.0設備上測試並且兩者都運行錯誤,我看到以下注釋但無法修復。

警報管理器示例 AlarmManager在錯誤的時間觸發警報 Android AlarmManager在錯誤的時間觸發

以下代碼:

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);

    }

如果我使用兩個同時定時器與ids 0和1的PendingIntent(但添加這些PendingIntent的結構與上面的代碼相同),但運行時間相同,為3分鍾。 兩者都在幾秒鍾內隨機執行錯誤的方式。

請改用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);
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM