如何在android

时间:2017-06-07 02:27:07

标签: java android timer

我正在创建一个Android测验游戏。我想为每个级别实现计时器,以计算用户可以快速回答所有问题的速度。在每个级别之间有一个活动,我想显示在进入下一个级别之前回答上一个级别的测验所花费的时间。我可以获得如何实现这一目标的指南吗?提前谢谢

1 个答案:

答案 0 :(得分:0)

You can do something like this, when the user starts quiz and enters into your first level, then inside onCreate take start time like this:

        Calendar calendar;
        SimpleDateFormat df;
        String template = "yyyy-MM-dd HH:mm:ss";
        calendar = Calendar.getInstance();
        df = new SimpleDateFormat(template, Locale.getDefault());

        //this will give you the start time
        String startTime = df.format(calendar.getTime());

        //when user finishes up the level again record the finish time
        String finishTime = df.format(calendar.getTime());

       //then compare the two times
        Date d1 = null;
        Date d2 = null;
        try {
            d1 = df.parse(startTime);
            d2 = df.parse(finishTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

       //in milliseconds
        long diff = d2.getTime() - d1.getTime();

        long diffSeconds = diff / 1000;
        long diffMinutes = diff / (60 * 1000);
        long diffHours = diff / (60 * 60 * 1000);

希望它有所帮助!!