简体   繁体   中英

Updating a widget every minute in Android Oreo

I have a widget that displays the current time and some other info, therefore it has to update once every minute. I am using an AlarmManager that triggers every minute and calls an IntentService that updates the widget. This solution works fine in Android versions prior to Oreo. On Oreo, this solution does not work - it looks like the AlarmManager is not firing. I have read that there is a TextClock control now that automatically updates the text to the current time but unfortunately this is not a solution since I need to draw other non-text information on the widget.

The alarm is set as follows:

if (android.os.Build.VERSION.SDK_INT >= 19) {
    alarmManager.setExact(AlarmManager.RTC, timeInMillis(), intent);

} else {
    alarmManager.setRepeating(AlarmManager.RTC, timeInMillis(), 1000 * 60, intent);
}

Note that the alarm is rescheduled every time it fires on android 19+ since it is not a repeating alarm.

Is there an alternative solution for the above to work in Android O and later?

If you are using simple TextViews to display the Clock, use a TextClock instead of TextView (added in API Level 17)

If you are using more complex Views (eg you draw a bitmap), you have to use a foreground service, which either uses explicit TIME_TICK receivers or Handlers to schedule the updates. You have to show a foreground notification and if not properly implemented, it could drain a lot of battery...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM