Finish work after a period of time

I am trying to develop a game similar to the coincidence of small pictures. My problem is that I want to finish the game after a period of time . For example, at level 1, we have 10 seconds to match the image. I also want to show the remaining time. I will be grateful for any help.

0
source share
3 answers

Since you also want to show the countdown, I would recommend CountDownTimer . This has methods to act on every tick, which may be the interval that you specified in the constructor. And its methods run on UI Thread, so you can easily update TextView, etc.

In this method, onFinish()you can call finish()for your own Activityor perform any other appropriate action.

See this answer for an example.

Edit with a clearer example

Here I have an inner class that extends CountDownTimer

@Override
public void onCreate(Bundle savedInstanceState) {
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.some_xml);      
    // initialize Views, Animation, etc...

    // Initialize the CountDownClass
    timer = new MyCountDown(11000, 1000);
}

// inner class
private class MyCountDown extends CountDownTimer
{
    public MyCountDown(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        frameAnimation.start();
        start();            
    }

    @Override
    public void onFinish() {
        secs = 10;
       // I have an Intent you might not need one
        startActivity(intent);
        YourActivity.this.finish(); 
    }

    @Override
    public void onTick(long duration) {
        cd.setText(String.valueOf(secs));
        secs = secs - 1;            
    }   
}
+4
source

@nKn described it pretty well.

However, if you do not want to communicate with Handler. You can always delay the progress of system code by writing:

Thread.sleep(time_at_mili_seconds);

, , try-catch, Source- > Surround → Try and catch.

0

postDelayed() Handler... a Thread , Thread , ...

private Handler mTimerHandler = new Handler();

private Runnable mTimerExecutor = new Runnable() {

    @Override
    public void run() {
        //here, write your code
    }
};

postDelayed() Handler , ...

 mTimerHandler.postDelayed(mTimerExecutor, 10000);
0

All Articles