我一直在按照教程制作 Android 应用程序小部件,但遇到了一些麻烦。教程引导我创建了这段代码:
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);
thisWidget = new ComponentName(context, FlipWidget.class);
}
@Override
public void run() {
remoteViews.setTextViewText(R.id.widget_text, "Time: "+format.format(new Date()));
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
}
但似乎永远不会调用 run 方法,因为 TextView 永远不会改变。感谢您的帮助,我很想了解 App Widgets。
尼克
最佳答案
首先,您不能使用Timer
。一旦 onUpdate()
返回,您的 AppWidgetProvider
和 Timer
将被垃圾回收。
其次,请不要每秒更新一个应用程序小部件。 android:updatePeriodMillis
的最小更新时间为 30 分钟是有原因的——将更新推送到应用小部件是一项昂贵的操作。每秒更新一个不仅会强制您的“更新应用程序小部件”代码有效地驻留在内存中并一直运行,而且还会显着消耗用户的电池电量。
对于应用小部件的定期更新,请使用 android:updatePeriodMillis
或使用 AlarmManager
。
关于android - App Widget 更新 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4378685/