我有一个TextView
来更新窗口小部件中的时间和日期,并尝试使用Timer
每秒更新一次,但它不起作用:
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);
}
}
我在某个地方出错了所以如果有人知道,请告诉我,并给我正确的方法来做到这一点。提前致谢
答案 0 :(得分:1)
尝试更新run()
中的app小部件 @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
尝试这样对我有用,我想在我使用的另一个应用程序中有相同的问题,而不是计时器和timertask使用:
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);