Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

android - Finish an activity after a time period

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 10 seconds to match picture.I want to display remaining time also.I will be thankful for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;            
    }   
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...