Skip to content Skip to sidebar Skip to footer

Widget Stops Updating After A Few Minutes

Im developing a widget that shows the time and date using two TextView using a timer to update every second: final Handler handler = new Handler(); Timer timer = new Timer(); timer

Solution 1:

As app widget is only a broadcast receiver hosted by the home screen process, you have to use AlarmManager for scheduling calls to your widget. If it is not just for testing be aware that your battery will drain because the device will never go to sleep state. Generally it is not a good idea to update app widgets every second.

It could be done (here for a wake up in one minute) similar to this code

AlarmManageram= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intentintent=newIntent(MyWidget.ACTION_MYACTION);
PendingIntentpi= PendingIntent.getBroadcast(context, 0, intent, 0);
longtriggerAtTime= getNextOccurrence(1); // next minute
am.set(AlarmManager.RTC_WAKEUP, triggerAtTime, pi);

and

staticprivatelonggetNextOccurrence(int deltaMinutes)
    {
            Calendarcalendar= Calendar.getInstance();
            longnow= calendar.getTimeInMillis();
            longthen= now + (deltaMinutes * 60 * 1000);
            return then;
    }

in OnReceive

public void onReceive(Context context, Intent intent)
    {
            Log.d(TAG, "onReceive() " + intent.getAction());
            super.onReceive(context, intent);

            if (intent != null)
            {
                    if (ACTION_MYACTION.equals(intent.getAction())
                    {
                            updateWidgets(context);
                    }
             ...

Post a Comment for "Widget Stops Updating After A Few Minutes"