有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在安卓中为循环添加延迟,而不会暂停UI线程

我已经查看了所有Android Studio文档和StackOverflow,但我似乎找不到一种方法来做与IOS中相同的事情: Adding Delay In A For Loop Without Blocking UI 在Android中

我尝试使用处理程序,但没有像下面那样运行代码:

// Iteration 1
// Delay of 500ms
// Iteration 2
// Delay of 500ms
// ...

代码的运行方式如下所示:

// Iteration 1
// Iteration 2
// Delay of 500ms
// next state

我使用的代码结构如下:

Handler myHandler = new Handler();
while (someCondition) {
    myHandler.postDelayed(new Runnable() {
        public void run() {
            myFunction();
        }
    }, 500);
}

我在运行此活动时看到的行为是跳过它,500毫秒后它进入下一个活动(具有预期的结果),但不向用户显示发生了什么

我如何延迟循环,以便用户可以看到发生了什么


克拉维:

在再次执行while循环的逻辑之前,需要显示当前状态(在moveCard()之后)x ms

直到达到最终状态为止

然后开始下一个活动


public void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.horserace_game);

    this.cardDeck = findViewById(R.id.deck);
    this.game_ended = false;

    this.deck = new Deck();
    this.aces = new ArrayList<>();
    this.acesPos = new ArrayList<>();
    this.hidden = new ArrayList<>();

    // Remove all Aces from deck and put them in aces
    //resetDeck creates a deck ordered on Face (so Ace SDHS, Two SDHS etc, which is handy for this purpose.
    this.deck.resetDeck(1);
    for (int i = 0; i < 4; i++) {
        this.aces.add(this.deck.removeCard(0));
        // Add a new pos for card
        this.acesPos.add(0);
    }

    // Shuffle the deck
    this.deck.shuffleDeck();

    // Get 7 cards from the top of the deck to put on the
    // side of the track and place them face down on the screen
    for (int i = 0; i < 7; i++) {
        this.hidden.add(this.deck.removeCard(0));
    }


    // Whilst the game is still running, pick a card from the deck and move the ace with the same suit
    while (!this.game_ended) {
        // Pick the next card from the deck
        this.next = this.deck.removeCard(0);
        cardDeck.setImageResource(getCardImage(next));
        // Find the ace with the same suit as this.next and set it's 'score'++
        for (Card ace : this.aces) {
            if (ace.getSuit().equals(next.getSuit())) {
                this.acesPos.set(ace.getSuit().ordinal(), this.acesPos.get(ace.getSuit().ordinal()) + 1);
                break;
            }
        }
        // Final state: the last ace now has a pos >7, this ace is the result. start new Activity
        if (this.acesPos.get(next.getSuit().ordinal()) > 7) {
            this.game_ended = true;
            Intent winner = new Intent();
            winner.putExtra("winner",next.getSuit().ordinal());

            setResult(RESULT_OK, winner);
            finish();
        // If the ace is not at it's final position, move it 
        // and pick a new card in the next iteration.
        } else {
            // Move card
            myHandler.postDelayed(new Runnable() {
                public void run() {
                    Log.e("run: ", "moveCard");
                    moveCard();
                }
            }, 500);
        }
    }
}

共 (3) 个答案

  1. # 1 楼答案

    moveCard()并等待移动到新目的地:

                while (!this.game_ended) {
            // Pick the next card from the deck
            this.next = this.deck.removeCard(0);
            cardDeck.setImageResource(getCardImage(next));
            // Find the ace with the same suit as this.next and set it's 'score'++
            for (Card ace : this.aces) {
                if (ace.getSuit().equals(next.getSuit())) {
                    this.acesPos.set(ace.getSuit().ordinal(), this.acesPos.get(ace.getSuit().ordinal()) + 1);
                    break;
                }
            }
            // Final state: the last ace now has a pos >7, this ace is the result. start new Activity
            if (this.acesPos.get(next.getSuit().ordinal()) > 7) {
                this.game_ended = true;
                myHandler.postDelayed(new Runnable() {
                    public void run() {
                       Intent winner = new Intent();
                        winner.putExtra("winner",next.getSuit().ordinal());
    
                        setResult(RESULT_OK, winner);
                        finish();
                   }
                }, 500);
            // If the ace is not at it's final position, move it 
            // and pick a new card in the next iteration.
            } else {
                // Move card
    
                        Log.e("run: ", "moveCard");
                        moveCard();
    
            }
        }
    
  2. # 2 楼答案

    考虑使用一个^ {CD1>},一个轮询模型,其中定时器将独立运行,并根据所定义的频率在其相关的^ {< CD2>}中执行代码。p>

        Timer timer = new Timer();
        timer.schedule (new TimerTask()
        {
         @Override public void run() 
         {
            // your program logic here
            if (game_ended)
              return;
            // Pick the next card from the deck
            next = deck.removeCard(0);
    .
    .
    .
         }
        }, 0, 500);
    

    这将立即启动计时器,触发器之间的延迟为500毫秒。每次计时器触发时,TimerTask中的run()方法都将执行

    onCreate中创建计时器,在onResume中启动/调度它,在onPause中停止。在TimerTask run()方法中,可以移动程序逻辑

  3. # 3 楼答案

    也许创造这样的东西应该管用

    protected static void startTimer() {
        timer.schedule(new TimerTask() {
            public void run() {
                mHandler.obtainMessage(1).sendToTarget();
            }
        }, 500);
    }
    
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
             myFunction();
        }
    };