簡體   English   中英

一段時間后,AlarmManager未設置或未在Marshmallow上觸發

[英]AlarmManager not set or not firing on Marshmallow after certain time

我已成功使用以下構造在我的一些Android應用程序中啟動AlarmManager:

    Intent serviceIntent = new Intent(context, MyService.class);
    PendingIntent pi = PendingIntent.getService(context, alarmId, serviceIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    DateTime inMinutes = (new DateTime()).plusMinutes(60);


    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    am.set(AlarmManager.RTC_WAKEUP, inMinutes.getMillis(), pi);

但是從Marshmallow開始,AlarmManager要么沒有設置,要么在一些空閑時間后不再觸發。 看起來當前正在運行的警報再次發出警報,但之后不會設置新的警報。

我讀了一些文檔,很可能是關於Marshmallow Doze。 所以我實現了以下(並檢查它實際上正在執行):

    Intent serviceIntent = new Intent(context, MyService.class);
    PendingIntent pi = PendingIntent.getService(context, alarmId, serviceIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    DateTime inMinutes = (new DateTime()).plusMinutes(minutes);


    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    if(Build.VERSION.SDK_INT >= 23)
        am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, inMinutes.getMillis(), pi);
    else {
        if(Build.VERSION.SDK_INT >= 19) {
            am.setExact(AlarmManager.RTC_WAKEUP, inMinutes.getMillis(), pi);
        } else {
            am.set(AlarmManager.RTC_WAKEUP, inMinutes.getMillis(), pi);
        }
    }

它沒有改變任何東西。

有一種可靠的方法可以在一些空閑時間后甚至在棉花糖上設置和發出警報嗎?

當然,試試:

       setAlarmClock(AlarmManager.AlarmClockInfo info, PendingIntent operation)

如果您以這種方式設置警報,則不會啟動打盹模式。我在控制台上對此進行了測試。

不要忘記,AlarmClock的信息有不同PendingIntentsetAlarmclock

UPDATE

如果你想做一個簡單的鬧鍾(不是鬧鍾)。

這必須工作

    setExactAndAllowWhileIdle(int type, long triggerAtMillis, PendingIntent operation)

但我現在卻沒有。 所以我開始尋找和谷歌,我發現了這一點。 添加應用程序打開白名單的可能方法。 也許setExactAndAllowWhileIdle工作。

https://developer.android.com/training/monitoring-device-state/doze-standby.html?hl=es

用戶可以在“設置”>“電池”>“電池優化”中手動配置白名單。 或者,系統提供應用程序要求用戶將其列入白名單的方法。

應用程序可以觸發ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS意圖,將用戶直接帶到Battery Optimization,在那里他們可以添加應用程序。 擁有REQUEST_IGNORE_BATTERY_OPTIMIZATIONS權限的應用可以觸發系統對話框,讓用戶直接將應用添加到白名單,而無需進行設置。 該應用程序觸發ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS Intent以觸發對話框。 用戶可以根據需要從白名單中手動刪除應用程序。 在要求用戶將您的應用添加到白名單之前,請確保該應用符合可接受的白名單用例。

暫無
暫無

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

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