在一段时间后完成一项活动



我正在尝试开发一个像匹配小图片的游戏。我的问题是我想在一段时间后完成游戏。例如,在关卡1中,我们有10秒的时间来匹配图片。我还想显示剩余时间。我将非常感谢您的帮助。

既然你也想显示倒计时,我建议使用CountDownTimer。它有方法在每次"滴答"时采取行动,这可以是您在构造函数中设置的间隔。它的方法运行在UI Thread上,所以你可以很容易地更新TextView,等等…

在它的onFinish()方法中,您可以为Activity调用finish()或执行任何其他适当的操作。

请看这个答案的例子

编辑更清晰的例子

这里我有一个内部类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;            
    }   
}

@nKn描述得很好。

但是,如果您不想乱搞Handler。您总是可以通过以下方式来延迟系统代码的进度:

Thread.sleep(time_at_mili_seconds);

你可能需要用Try -catch包围它,你可以通过Source-> surround with -> Try &div。

可以使用HandlerpostDelayed()方法…传递Thread和特定时间,之后Thread将按如下方式执行…

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

然后调用HandlerpostDelayed()方法在指定时间后执行,如下所示…

 mTimerHandler.postDelayed(mTimerExecutor, 10000);

最新更新