Androidで遅延を設定するにはどうすればよいですか?


164
public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId()){
        case R.id.rollDice:
            Random ranNum = new Random();
            int number = ranNum.nextInt(6) + 1;
            diceNum.setText(""+number);
            sum = sum + number;
            for(i=0;i<8;i++){
                for(j=0;j<8;j++){

                    int value =(Integer)buttons[i][j].getTag();
                    if(value==sum){
                        inew=i;
                        jnew=j;

                        buttons[inew][jnew].setBackgroundColor(Color.BLACK);
                                                //I want to insert a delay here
                        buttons[inew][jnew].setBackgroundColor(Color.WHITE);
                         break;                     
                    }
                }
            }


            break;

        }
    }

コマンドの背景を変更する間隔を設定します。スレッドタイマーを使用して、実行とキャッチを使用してみました。しかし、それは機能していません。私はこれを試しました

 Thread timer = new Thread() {
            public void run(){
                try {
                                buttons[inew][jnew].setBackgroundColor(Color.BLACK);
                    sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

             }
           };
    timer.start();
   buttons[inew][jnew].setBackgroundColor(Color.WHITE);

しかし、黒に変わっているだけです。

回答:


499

このコードを試してください:

import android.os.Handler;
...
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Do something after 5s = 5000ms
        buttons[inew][jnew].setBackgroundColor(Color.BLACK);
    }
}, 5000);

1
このソリューションは、コードのいくつかの行でハンドラーに関して私が持っていたすべての質問を説明しました。
Sierisimo、2015年

45
毎回書くのが面倒なので、いつもこの投稿に戻ります。ありがとうございました。
Eugene H

よくそれはよろしいですが、私は待ってから表示するメッセージがたくさんあります。そのため、マルチブルトレッドは問題を引き起こします。複数の踏み板の問題を解決するには
mehmet

2
このソリューションは、外部クラスであるアクティビティへの参照を暗黙的に保持する非静的内部および匿名クラスを使用するため、メモリリークが発生します。より優れたソリューションについては、stackoverflow.com / questions / 1520887 /…を参照してください。
トロンマン2017

簡単に生活のための@EugeneH使用ライブテンプレートstackoverflow.com/a/16870791/4565796
サイードArianmanesh

38

CountDownTimer投稿されている他のどのソリューションよりもはるかに効率的な方法を使用できます。そのonTick(long)方法を使用して、途中で定期的に通知を生成することもできます

30秒のカウントダウンを示すこの例をご覧ください

   new CountDownTimer(30000, 1000) {
         public void onFinish() {
             // When timer is finished 
             // Execute your code here
     }

     public void onTick(long millisUntilFinished) {
              // millisUntilFinished    The amount of time until finished.
     }
   }.start();

23

アプリで遅延を頻繁に使用する場合は、このユーティリティクラスを使用してください

import android.os.Handler;


public class Utils {

    // Delay mechanism

    public interface DelayCallback{
        void afterDelay();
    }

    public static void delay(int secs, final DelayCallback delayCallback){
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                delayCallback.afterDelay();
            }
        }, secs * 1000); // afterDelay will be executed after (secs*1000) milliseconds.
    }
}

使用法:

// Call this method directly from java file

int secs = 2; // Delay in seconds

Utils.delay(secs, new Utils.DelayCallback() {
    @Override
    public void afterDelay() {
        // Do something after delay

    }
});

1
どうして ?これは純粋なオーバーヘッドと複雑さです...何のためにも
juloo65

頻繁に遅延を使用する場合は、遅延の形式を固定しておくのが適切です。インターフェースとメソッドが1つ追加されているため、オーバーヘッドはそれほど大きくないと思います。
aruke

18

Thread.sleep(millis)メソッドを使用します。


30
UIスレッドでこれを行わないでください-他の要素も応答を停止し、後で予測できない動作をする可能性があります
jmaculate

1
警告をありがとう。それがまさに私が必要としていることであり、UIスレッドを遅らせるためです。私のニーズにぴったりの答えです。ありがとう。
2014

7

定期的にUIで何かを実行したい場合は、CountDownTimerを使用するのが非常に良い方法です。

new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();

ハンドラーよりもきれいです。
Ahsan

3

Kotlinのハンドラー応答:

1- ファイル内にトップレベル関数を作成します(たとえば、すべてのトップレベル関数を含むファイル):

fun delayFunction(function: ()-> Unit, delay: Long) {
    Handler().postDelayed(function, delay)
}

2-次に、必要な場所に呼び出します。

delayFunction({ myDelayedFunction() }, 300)

2

あなたはこれを使うことができます:

import java.util.Timer;

そして遅延自体のために、追加します:

 new Timer().schedule(
                    new TimerTask(){
                
                        @Override
                        public void run(){
                            
                        //if you need some code to run when the delay expires
                        }
                        
                    }, delay);

ここで、delay変数はミリ秒単位です。たとえばdelay、5秒の遅延の場合は5000に設定します。


0

これは、背景画像を2秒のアルファフェードディレイで双方向に変更する例です-元の画像の2秒のフェードアウトから2番目の画像の2秒のフェードインへ。

    public void fadeImageFunction(View view) {

    backgroundImage = (ImageView) findViewById(R.id.imageViewBackground);
    backgroundImage.animate().alpha(0f).setDuration(2000);

    // A new thread with a 2-second delay before changing the background image
    new Timer().schedule(
            new TimerTask(){
                @Override
                public void run(){
                    // you cannot touch the UI from another thread. This thread now calls a function on the main thread
                    changeBackgroundImage();
                }
            }, 2000);
   }

// this function runs on the main ui thread
private void changeBackgroundImage(){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            backgroundImage = (ImageView) findViewById(R.id.imageViewBackground);
            backgroundImage.setImageResource(R.drawable.supes);
            backgroundImage.animate().alpha(1f).setDuration(2000);
        }
    });
}
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.