我有一个小部件即时尝试使用计时器更新TextView
:
public void onUpdate(Context context, final AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
final 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.scheduleAtFixedRate(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));
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}, 0, 1000);// Update textview every second
}
}
问题是,它只会更新一次,之后再也不会。我哪里错了?
答案 0 :(得分:2)
您应该使用Handler,从时间任务中对UI线程进行操作。
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
//Your code here
}});
}
}, 0, 1000);// Update textview every second
此外,您应该像on this(
)一样在onCreate()中启动Handlerhandler = new Handler();
答案 1 :(得分:1)
int _count=0;
_tv = (TextView) findViewById( R.id.textView1 );
_tv.setText( "red" );
_t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
@Override
public void run() {
_count++;
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
_tv.setText(""+_count);
}
});
}
}, 1000, 1000 );