Danny Buonocore
Danny Buonocore

Reputation: 3777

AppWidget update once a minute

I have an Android AppWidget that I would like to update once a minute. So in The AppWidgetProvider I create a repeating alarm set to trigger once every 60 seconds. At first it seems fine. For the first 10 minutes or so it updates almost exactly once a minute. But then it slows down and only updates about every 3-5 minutes. I'm wondering if this is an issue with the way I have the AppWidget set up, or if I'm initializing the timer incorrectly. It also doesn't seem to update in regular intervals after the slow down.

AppWidgetProvider

private PendingIntent service = null;

@Override
public void onUpdate(Context context,
    AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    startAlarm(context);
}

@Override
public void onEnabled(Context context) {
    startAlarm(context);
}

@Override
public void onDisabled(Context context) {
    // TODO: disable alarm
}

private void startAlarm(Context context) {
    Log.d(TAG, "Starting alarm");

    final AlarmManager m =
        (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    final Intent i = new Intent(context, MyService.class);

    if (service == null)
        service = PendingIntent.getService(context, 0, i,
                PendingIntent.FLAG_CANCEL_CURRENT);

    m.setRepeating(AlarmManager.RTC, System.currentTimeMillis() + (1000 * 10),
            1000 * 60, service);
}

MyService

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "Service started");
    buildUpdate();

    return super.onStartCommand(intent, flags, startId);
}

private void buildUpdate() {

    // Do stuff.

}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

This is being run on my Samsung Galaxy S7 API level 23 if that is relevant. Thanks in advance!

Upvotes: 2

Views: 1904

Answers (2)

ra3o.ra3
ra3o.ra3

Reputation: 852

What is your targetSdkVersion? Beginning with API 19 (Kitkat) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use.

For exact alarms, in case your targetSdkVersion is 19 or later, you have to use setExact(...). There is no exact version of setRepeating(...)

For Applications whose targetSdkVersion is earlier than API 19 setRepeating(...) will still deliver exact alarms.

Upvotes: 1

HeyAlex
HeyAlex

Reputation: 1746

Actually if you need update widget more than one time per 30 mins, the best approach to use IntentService that will update your widget (alarm on it). Same approach i use at my library for widgets which i use on internal and my projects (since it's gonna like a pattern which i can use on every project with widgets). Actually i didn't find any problems with your code (maybe you can make a small sample project from your code).

Upvotes: 1

Related Questions