안드로이드에서 지연을 설정하는 방법?


165
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;

        }
    }

배경 변경 사이의 명령 사이에 지연을 설정하고 싶습니다. 스레드 타이머를 사용하고 run and catch를 사용해 보았습니다. 그러나 작동하지 않습니다. 나는 이것을 시도했다

 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);

그러나 검은 색으로 만 바뀌고 있습니다.

답변:


500

이 코드를 사용해보십시오 :

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

45
매번 글을 쓰기에는 너무 게으 르기 때문에 항상이 게시물로 돌아옵니다. 감사합니다.
— Eugene H

잘 그것은 llok 멋지지만 나는 보여줄 많은 메시지가 있습니다. 따라서 여러 번 밟으면 문제가 발생합니다. 여러 자국의 문제를 해결할 수있는 방법
— 메 흐멧

2
이 솔루션은 외부 클래스, 활동에 대한 참조를 내재적으로 보유하는 정적이 아닌 내부 및 익명 클래스를 사용하므로 메모리 누수가 발생합니다. 더 나은 솔루션 은 stackoverflow.com/questions/1520887/… 을 참조하십시오 .
— tronman

쉽게 생활에 대한 @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

빈번한 지연을 사용하면 지연에 대한 고정 형식을 갖는 것이 좋습니다. 하나의 추가 인터페이스와 방법으로 인해 많은 오버 헤드가 있다고 생각하지 않습니다.
— aruke

18

Thread.sleep(millis)방법을 사용합니다 .


30
UI 스레드에서이 작업을 수행하지 마십시오. 다른 요소도 응답을 중지하고 나중에 예기치 않게 동작 할 수 있습니다
— jmaculate

1
경고 주셔서 감사합니다. UI 스레드를 지연시키는 데 필요한 것입니다. 내 필요에 대한 완벽한 답변. 감사.
— hamish

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();

Handler 보다 깨끗합니다 .
— Ahsan

3

코 틀린의 핸들러 답변 :

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변수는 밀리 초입니다. 예를 들어 delay5 초 지연의 경우 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.