Programming

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

procodes 2020. 6. 8. 21:50
반응형

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


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

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


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

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

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

앱에서 지연을 자주 사용하는 경우이 유틸리티 클래스를 사용하십시오.

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

    }
});

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


규칙적인 시간 간격으로 UI에서 무언가를하고 싶다면 CountDownTimer를 사용하는 것이 좋습니다.

new CountDownTimer(30000, 1000) {

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

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

이것을 사용할 수 있습니다 :

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" variable represents milliseconds , for example set delay to 5000 - for a 5 seconds delay


Handler answer in Kotlin :

1 - Create a top-level function inside a file (for example a file that contains all your top-level functions) :

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

2 - Then call it anywhere you needed it :

delayFunction({ myDelayedFunction() }, 300)

Here's an example where I change the background image from one to another with a 2 second alpha fade delay both ways - 2s fadeout of the original image into a 2s fadein into the 2nd image.

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

참고URL : https://stackoverflow.com/questions/15874117/how-to-set-delay-in-android

반응형