如何在android studio中正确使用postDelayed()?

Ryd*_*ker 23 android handler postdelayed android-handler

我有一个countDownTimer,如果用户在第12秒内没有点击gameButton我想要调用gameOver方法.问题当countDownTimer为12或者计时器只是不断倒计时,我或者得到名为instamtly的游戏功能.所以我试图使用postDelayed()方法给用户一个完整的秒来点击按钮并让countDownTimer继续,但正如我的代码现在,游戏停在12无论如何.

import android.app.Activity;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;



public class GameScreen extends Activity {

    private TextView time;
    private Button start;
    private Button cancel;
    private Button gameButton;
    private CountDownTimer countDownTimer;
    public static int count = 0;
    public static int countFail = 0;

    final Handler handler = new Handler();
    final Runnable r = new Runnable() {
        public void run() {
            handler.postDelayed(this, 1000);
            gameOver();
        }
    };


    private View.OnClickListener btnClickListener = new View.OnClickListener(){

        @Override
        public void onClick(View v) {

            switch(v.getId()){
                case R.id.start_ID :
                    start();
                    break;
                case R.id.cancel :
                    cancel();
                    break;
                case R.id.gameButton_ID :
                    gameButton();
                    break;
            }

        }


    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_screen);


        start = (Button) findViewById(R.id.start_ID);
        start.setOnClickListener(btnClickListener);
        cancel = (Button) findViewById(R.id.cancel);
        cancel.setOnClickListener(btnClickListener);
        time = (TextView) findViewById(R.id.time);
        gameButton = (Button) findViewById(R.id.gameButton_ID);
        gameButton.setOnClickListener(btnClickListener);


    }

    public void start(){

        time.setText("16");
        //This doesn't work and makes app crash when you hit start button

        countDownTimer = new CountDownTimer(16 * 1000, 1000) {
            @Override
            public void onTick(long millsUntilFinished){
                time.setText("" + millsUntilFinished / 1000);

                //turns textview string to int
                int foo = Integer.parseInt(time.getText().toString());

                if(time.getText().equals("12")){

                    r.run();

                }

            }

            public void onFinish() {
                time.setText("Done !");
            }
        };
        countDownTimer.start();
    }

    private void cancel(){
        if(countDownTimer != null){
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }

    private void gameOver(){
        Toast.makeText(getApplicationContext(), "You scored " + count, Toast.LENGTH_SHORT).show();
        count = 0;
        countFail = 0;
        cancel();
    }

    private void gameButton(){

        int foo = Integer.parseInt(time.getText().toString());

        if(foo  % 2 == 0 ) {
            Toast.makeText(getApplicationContext(), "PASS", Toast.LENGTH_SHORT).show();
            handler.removeCallbacks(r);
            ++count;
        }

        else{
            gameOver();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Dan*_*eDC 55

你几乎postDelayed(Runnable, long)正确使用,但不完全正确.我们来看看你的Runnable.

final Runnable r = new Runnable() {
    public void run() {
        handler.postDelayed(this, 1000);
        gameOver();
    }
};
Run Code Online (Sandbox Code Playgroud)

当我们调用r.run();第一件事时,它要告诉你handler在1000毫秒后运行相同的Runnable,然后调用gameOver().这实际上会导致你的gameOver()方法被调用两次:一次立即调用,第二次处理程序完成后等待1000毫秒.

相反,您应该将Runnable更改为:

final Runnable r = new Runnable() {
    public void run() {
        gameOver();
    }
};
Run Code Online (Sandbox Code Playgroud)

并称之为:

handler.postDelayed(r, 1000);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

  • “gameOver()”不是每秒无限次调用,而不是被调用两次吗?看起来像是无限递归。 (3认同)

Bip*_*Das 9

Thread(Runnable {
    // background work here ... 
    Handler(Looper.getMainLooper()).postDelayed(Runnable {
        // Update UI here ...
    }, 10000) // It will wait 10 sec before updating UI
}).start()
Run Code Online (Sandbox Code Playgroud)


Ris*_*ava 7

下面是我使用的代码,该代码与接受的答案相同,但是编写和理解起来非常简单。

final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Write whatever to want to do after delay specified (1 sec)
                    Log.d("Handler", "Running Handler");
                }
            }, 1000);
Run Code Online (Sandbox Code Playgroud)