0

I had a widget with a countdown timer what worked fine in Android 4.1. But I tried in 5.1 and its not working anymore. Reading blogs and the documentation its a change in that android version

This is my code in my onEnabled in the AppWidgetProvider class

@Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
        AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ 100 * 1, 1000 , pi);
    }

I read that setRepeating is not more support and I should use setExact or something. It didnt work too.

The best solution is implement a WakefulBroadcastReceiver but I dont know how to launch his onReceive method every second to update the widget.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
benoffi7
  • 3,068
  • 3
  • 29
  • 44
  • This is the post that I read https://stackoverflow.com/questions/34074955/android-exact-alarm-is-always-3-minutes-off/34085645 https://code.google.com/p/android/issues/detail?id=82001 – benoffi7 Oct 30 '16 at 11:56
  • I use this code as base of my app http://code4reference.com/2012/07/android-homescreen-widget-with-alarmmanager/ an it works on Android 4.1 – benoffi7 Oct 30 '16 at 11:57

1 Answers1

2

I had a widget with a countdown timer what worked fine in Android 4.1

I sincerely hope that this timer was for short things. Doing something every second is fairly evil, particularly when your app widget is hidden the vast majority of the time. Google is having to take steps to prevent developers from doing things like this.

This is my code in my onEnabled in the AppWidgetProvider class

One of the things that Google did to prevent developers from doing things like this is add an undocumented change in Android 5.1, where setRepeating() cannot have a period of less than one minute.

I should use setExact or something. It didnt work too.

I think that you might be able to get down to every-five-second granularity that way. It's better than setRepeating(), but I don't think you can go down to every-second granularity.

The best solution is implement a WakefulBroadcastReceiver

That will not address your problem.

You can fire up a foreground service and use some in-process timing engine (e.g., ScheduledExecutorService) to get control every second and update your app widget. Just bear in mind that:

  • Your service will not live forever

  • Sleep mode, Doze mode, app standby, and the like will still prevent your code from running

  • I would not be shocked if Google takes steps to block this sort of behavior too, in some future version of Android

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491