簡體   English   中英

如何停止 android 中的定時器

[英]how to stop the timer in android

這是我的代碼,我正在我的圖像視圖中動態更改一些圖像。 公共 class LoadingScreen 擴展活動{

public static Integer[] imageList={R.drawable.food_pics1,R.drawable.food_pics2,R.drawable.food_pics3,
    R.drawable.food_pics4,R.drawable.food_pics5,R.drawable.food_pics6,R.drawable.food_pics7,
    R.drawable.food_pics8,R.drawable.food_pics9};
Thread thread;
ImageView foodImageView;
final Handler myHandler=new Handler();
public int currentImageIndex=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.load_xml);
    foodImageView=(ImageView)findViewById(R.id.imageView_food);
    //      final int i=0;

    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            animateImages();
        }


    };

    final int delay=500;            
    final long period=1000;
    Timer timer=new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            myHandler.post(runnable);
        }
    }, delay, period);
}

private void animateImages() {
    // TODO Auto-generated method stub
        foodImageView.setImageResource(imageList[currentImageIndex%imageList.length]);
        currentImageIndex++;
        foodImageView.getAnimation();
}

我想停止計時器並在 20 秒后完成此活動。我該怎么做。

嘗試使用這個,

 View v = new View(this);
        v.postDelayed(new Runnable(){
            public void run() {
                // TODO Auto-generated method stub
                //cancel your animation and finish the Activity here.
                finish();
            }
         }, (long) 20000.0);

你可以這樣說:

timer.cancel();
timer = null;

將 TimerTask 實例保存在 class 中並對其調用取消

這是我在使用 Java 計時器的情況下發現非常有用的提示:嘗試在 UI 線程中同步事物,特別是如果您想執行 UI 任務。 例子:

... onCreate() {
getUiThreadHandler().post(new Runnable(){
  if (canceled()) {
    return;
  }

  // Actual work
  ...

  // Invoke again after delay
  getUiThreadHandler().postDelayed(this, 500);
});

祝你好運

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM