App Widget update TextView
I have been following a tutorial to make Android App Widgets, and I was having a little trouble. The tutorial led me to create this code:
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int [] appWidgetIds) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTime(context, appWidgetManager), 1, 1000);
}
private class MyTime extends TimerTask {
RemoteViews remoteViews;
AppWidgetManager appWidgetManager;
ComponentName thisWidget;
DateFormat format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM, Locale.getDefault());
public MyTime(Context context, AppWidgetManager appWidgetManager) {
this.appWidgetManager = appWidgetManager;
remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
thi开发者_如何学编程sWidget = new ComponentName(context, FlipWidget.class);
}
@Override
public void run() {
remoteViews.setTextViewText(R.id.widget_text, "Time: "+format.format(new Date()));
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
}
but it seems that the run method is never being called, as the TextView never changes. Thanks for your help, I'd love to get a handle on App Widgets.
Nick
First, you cannot use Timer
. Your AppWidgetProvider
, and the Timer
, will be garbage-collected once onUpdate()
returns.
Second, please do not update an app widget every second. There is a reason why android:updatePeriodMillis
has a 30-minute minimum -- pushing updates to app widgets is an expensive operation. Updating one every second would not only force your "update an app widget" code to effectively be resident in memory and running all of the time, but you will also whack the user's battery pretty significantly.
For periodic updates of an app widget, either use android:updatePeriodMillis
or use AlarmManager
.
精彩评论