0

我想在 appWidget 上显示简单的动画。

动画是由 2 位图制作的。

Resources r = getResources();
         Bitmap ani[] = {BitmapFactory.decodeResource(r, R.drawable.anime1),BitmapFactory.decodeResource(r, R.drawable.anime2)};

有柜台

int counter = 0;

这是 TimerTask 中的运行方法。

    @Override
            public void run() {
                AppWidgetManager awm = AppWidgetManager.getInstance(getApplicationContext());
                ComponentName cn = new ComponentName(getApplicationContext(), sample.class);
                RemoteViews rv = new RemoteViews(getApplicationContext().getPackageName(), R.layout.mainlayout);
                rv.setImageViewBitmap(R.id.material, ani[counter]);
                awm.updateAppWidget(cn, rv);
counter++;

            }

当我timer.schedule与他们一起执行时,我怎样才能停止这个计数器==2?

4

4 回答 4

2

You should stop the timer inside the run of timertask after checking the condition.

    TimerTask timerTask=new TimerTask() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        if(counter==2){
        timer.cancel();
        }
    }
};

The timer should be like this.

Timer timer=new Timer();
timer.scheduleAtFixedRate(timerTask, when, period);

Hope this will help you.

于 2013-04-23T09:56:56.600 回答
2

我不确定你需要什么。如果计数器达到 2,我假设您需要取消。

    int count=0;
    _t = new Timer();
    _tv.setText(""); 
    _t.scheduleAtFixedRate( new TimerTask() {
            @Override
            public void run() {
                _count++;

                runOnUiThread(new Runnable() //run on ui thread
                 {
                  public void run() 
                  { 

                      _tv.setText(""+_count);
                      if(_count==2)
                      {
                          _t.cancel();
                      }
                 }
                 });
            }
        }, 1000, 1000 ); 

您也可以使用处理程序。使用计时器任务将创建一个新线程。更新 ui 应该在 UI Thread 上完成。最好使用处理程序。

于 2013-04-23T09:47:09.520 回答
0

不要使用 TimerTask,而是使用 Handler 来完成此类任务

于 2013-04-23T10:00:50.687 回答
0
if(counter == 2)
{
    timer.cancel();
}
于 2013-04-23T09:54:44.093 回答