Simple way To Update Widget TextView Periodically

被刻印的时光 ゝ 提交于 2019-12-07 23:50:48

问题


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().



来源:https://stackoverflow.com/questions/15317600/simple-way-to-update-widget-textview-periodically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!