Finish an activity after a time period

后端 未结 3 2068
执笔经年
执笔经年 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;            
        }   
    }
    

提交回复
热议问题