1

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.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {

            handler.post(new Runnable() {
                    public void run() {
                        java.util.Date noteTS = Calendar.getInstance().getTime();
                        String time = "kk:mm";
                        String date = "dd MMMMM yyyy";

                        views.setTextViewText(R.id.tvTime, DateFormat.format(time, noteTS));
                        views.setTextViewText(R.id.tvDate, DateFormat.format(date, noteTS));
                        appWidgetManager.updateAppWidget(appWidgetId, views);
                    }
            });
    }
}, 0, 1000);// Update textview every second

It updates the widget when added but stops after a few minutes. Also it struggles to load after I reboot but the main problem is it seems the timer stops after so many minutes... Anyone know what is going on? Thanks

Timmo
  • 2,266
  • 4
  • 34
  • 54

1 Answers1

0

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

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MyWidget.ACTION_MYACTION);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
long triggerAtTime = getNextOccurrence(1); // next minute
am.set(AlarmManager.RTC_WAKEUP, triggerAtTime, pi);

and

static private long getNextOccurrence(int deltaMinutes)
    {
            Calendar calendar = Calendar.getInstance();
            long now = calendar.getTimeInMillis();
            long then = 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);
                    }
             ...
j.holetzeck
  • 4,048
  • 2
  • 21
  • 29
  • Can i get a way to do this in my case? Or maybe an example that I can interpret to my own code – Timmo Apr 01 '13 at 21:29