วิธีตั้งค่าหน่วงเวลาใน Android


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;

        }
    }

ฉันต้องการตั้งค่าการหน่วงเวลาระหว่างคำสั่งระหว่างการเปลี่ยนพื้นหลัง ฉันลองใช้ตัวจับเวลาเธรดและลองใช้การเรียกใช้และจับ แต่มันไม่ทำงาน ฉันลองสิ่งนี้

 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
ฉันมักจะกลับมาที่โพสต์นี้เพราะฉันขี้เกียจเกินกว่าจะเขียนทุกครั้ง ขอบคุณ.
ยูจีน H

มันดี llok ดี แต่ฉันมีข้อความจำนวนมากที่จะรอแล้วแสดง ดอกยางหลายชั้นจึงมีปัญหา วิธีการที่สามารถแก้ปัญหาหลายดอกยาง
mehmet

2
โซลูชันนี้สร้างการรั่วไหลของหน่วยความจำเนื่องจากใช้คลาสภายในและไม่ระบุชื่อแบบไม่คงที่ซึ่งมีการอ้างอิงถึงกิจกรรมภายนอกคลาสโดยนัย ดูstackoverflow.com/questions/1520887/…สำหรับวิธีแก้ปัญหาที่ดีกว่า
tronman

@EugeneH ใช้เทมเพลตสดเพื่อชีวิตที่ง่ายขึ้นstackoverflow.com/a/16870791/4565796
Saeed 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

ตัวจัดการคำตอบใน 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เป็น 5000 สำหรับการหน่วงเวลา 5 วินาที


0

นี่คือตัวอย่างที่ฉันเปลี่ยนภาพพื้นหลังจากที่หนึ่งไปยังอีกด้วย 2 วินาที alpha fade หน่วงเวลาทั้งสองวิธี - fadeout 2 วินาทีของภาพต้นฉบับเป็น fadein 2s เป็นภาพที่ 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.