Finish an activity after a time period

后端 未结 3 2025
执笔经年
执笔经年 2020-11-30 15:45

I am trying to develop a game like matching small pictures.My problem is that i want to finish the game after a time period.For instance in level 1 we have

相关标签:
3条回答
  • 2020-11-30 16:25

    Since you also want to show the countdown, I would recommend a CountDownTimer. This has methods to take action at each "tick" which can be an interval you set in the constructor. And it's methods run on the UI Thread so you can easily update a TextView, etc...

    In it's onFinish() method you can call finish() for your Activity or do any other appropriate action.

    See this answer for an example

    Edit with more clear example

    Here I have an inner-class which 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;            
        }   
    }
    
    0 讨论(0)
  • 2020-11-30 16:29

    You can use postDelayed() method of Handler...pass a Thread and specific time after which time the Thread will be executed as below...

    private Handler mTimerHandler = new Handler();
    
    private Runnable mTimerExecutor = new Runnable() {
    
        @Override
        public void run() {
            //here, write your code
        }
    };
    

    Then call postDelayed() method of Handler to execute after your specified time as below...

     mTimerHandler.postDelayed(mTimerExecutor, 10000);
    
    0 讨论(0)
  • 2020-11-30 16:34

    @nKn described it pretty well.

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

    Thread.sleep(time_at_mili_seconds);
    

    You probably need to surround it with try-catch, which you can easily add via Source-> Surround with --> Try & catch.

    0 讨论(0)
提交回复
热议问题