1

Ive got a TextView to update the time and date in a widget and have attempted to use a Timer to update it every second but it isnt working:

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    final int N = appWidgetIds.length;

    for (int i = 0; i < N; i++) {
        int appWidgetId = appWidgetIds[i];

        Intent clockIntent = new Intent(context, DeskClock.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, clockIntent, 0);

        final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.digitalclock);
        views.setOnClickPendingIntent(R.id.rl, pendingIntent);

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            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));
            }
        }, 0, 1000);// Update text every second

        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}

Im going wrong somewhere so if anyone knows, let me know and give me the right way to do this. Thanks in advance

4

1 回答 1

1

try to update the app widget inside the run()

        @Override
        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 text every second

try it like this this works for me, i think i had the same issue in another app i was using, instead of a timer and timertask use:

Handler mHandler;
Runnable continuousRunnable = 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);

            mHandler.postDelayed(this, 1000);
        }
    };
  mHandler.post(continuousRunnable);
于 2013-03-31T00:33:48.927 回答