Search code examples
androidandroid-widget

Updating Android widgets every 1 minute


I'm writing an Android widget. I want to update it every 1-5 minutes to monitor data from web service but I discovered that android:updatePeriodMillis cannot be less than 30 minutes.

How can I obtain this result with a widget?


Solution

  • Register an AlarmManager service for every 1 min call.

    final Intent intent = new Intent(context, UpdateService.class);
    final PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
    final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarm.cancel(pending);
    long interval = 1000*60;
    alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),interval, pending);
    

    However, pushing updates to app widgets is an expensive operation. Updating every 1 min would force your "update an app widget" code to be resident in memory which keeps running all of the time, and this will also eat up battery pretty significantly.