Simple way To Update Widget TextView Periodically

2019-05-24 06:46发布

问题:

I have a widget with two TextView showing the time and date.

I simply want this batch of code to happen every second:

views.setOnClickPendingIntent(R.id.rl, pendingIntent);
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));

So I need a simple way to update TextView periodically in the widget so the time changes more than the standard 30 mins. Thanks

回答1:

you may create Handler and Runnable, and then let the Handler to restart your Runnable at the specified interval. your program might look like this:

private Handler mHandler = new Handler();

@Override
public void onResume() {
    super.onResume();
    mHandler.removeCallbacks(mUpdateClockTask);
    mHandler.postDelayed(mUpdateCLockTask, 100);
}

@Override
public void onPause() {
    super.onPause();
    mHandler.removeCallbacks(mUpdateClockTask);
}

private Runnable mUpdateClockTask = new Runnable() {
    public void run() {
        updateClock();
        mHandler.postDelayed(mUpdateClockTask, 1000);
    }
};

and inside updateClock() you do all your UI updates. I suppose all this happens inside the Activity with the appropriate onPause()/onResume() calls.



回答2:

u have to use AlarmManager, check this tutorial for details: http://www.vogella.com/articles/AndroidWidgets/article.html#widget_update dont forget to check this part:

8. Tutorial: Update widget via a service



回答3:

Another possibility would be the use of the Timer and TimerTask classes. You can use the Timer.schedule(TimerTask task, long delay, long period) method to accomplish what you need.

Keep in mind that you cannot access the UI thread from within a TimerTask - so the Handler.postDelayed() method might be a better bet if you already intend to use a Handler with the Timer class. There are other methods for accessing the UI thread with a TimerTask, such as Activity.runOnUiThread().