Android倒数计时器到目前为止

时间:2012-08-09 01:05:02

标签: java android eclipse android-layout android-intent

我正在尝试为Android中的游戏/日期制作倒数计时器。我想创建一个计时器,显示我用最终变量指定的日期的天,小时,分钟和秒。然后,计时器设置文本视图以显示用户的日期,小时,分钟和秒。

有关我如何对此进行编码的任何建议?

8 个答案:

答案 0 :(得分:14)

CountDownTimer将显示格式化为小时,分钟,天和秒的时间。

 public class DemotimerActivity extends Activity {
        /** Called when the activity is first created. */
         TextView tv;
         long diff;
         long oldLong;
         long NewLong;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            tv = new TextView(this);
            this.setContentView(tv);
            SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm");
            String oldTime = "19.02.2018, 12:00";//Timer date 1
            String NewTime = "20.02.2018, 14:00";//Timer date 2
            Date oldDate, newDate;
            try {
                oldDate = formatter.parse(oldTime);
                newDate = formatter.parse(NewTime);
                oldLong = oldDate.getTime();
                NewLong = newDate.getTime();
                diff = NewLong - oldLong;
           } catch (ParseException e) {
                e.printStackTrace();
       }
         MyCount counter = new MyCount(diff, 1000);
         counter.start();
    }


    // countdowntimer is an abstract class, so extend it and fill in methods
    public class MyCount extends CountDownTimer {
    MyCount(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onFinish() {
        txtNumber1.setText("done!");
    }

    @Override
    public void onTick(long millisUntilFinished) {
         long millis = millisUntilFinished;
        String hms = (TimeUnit.MILLISECONDS.toDays(millis)) + "Day "
                + (TimeUnit.MILLISECONDS.toHours(millis) - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(millis)) + ":")
                + (TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)) + ":"
                + (TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));
        txtNumber1.setText(/*context.getString(R.string.ends_in) + " " +*/ hms);
    }
}

    }

答案 1 :(得分:8)

试试这个:

SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss");
        formatter.setLenient(false);


        String endTime = "25.06.2017, 15:05:36"

        Date endDate;
        try {
            endDate = formatter.parse(endTime);
            milliseconds = endDate.getTime();

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

         startTime = System.currentTimeMillis();

         diff = milliseconds - startTime;


           mCountDownTimer = new CountDownTimer(milliseconds, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

                startTime=startTime-1;
                Long serverUptimeSeconds =
                        (millisUntilFinished - startTime) / 1000;

                String daysLeft = String.format("%d", serverUptimeSeconds / 86400);
                txtViewDays.setText(daysLeft);

                String hoursLeft = String.format("%d", (serverUptimeSeconds % 86400) / 3600);
                txtViewHours.setText(hoursLeft);

                String minutesLeft = String.format("%d", ((serverUptimeSeconds % 86400) % 3600) / 60);

                txtViewMinutes.setText(minutesLeft);

                String secondsLeft = String.format("%d", ((serverUptimeSeconds % 86400) % 3600) % 60);
                txtViewSecond.setText(secondsLeft);


            }

            @Override
            public void onFinish() {

            }
        }.start();

    }

答案 2 :(得分:5)

这是一个Android内置的CountDownTimer,它将在TextView中显示格式化为日,小时,分钟和秒的时间:

public class Example extends Activity {
    CountDownTimer mCountDownTimer;
    long mInitialTime = DateUtils.DAY_IN_MILLIS * 2 + 
                        DateUtils.HOUR_IN_MILLIS * 9 +
                        DateUtils.MINUTE_IN_MILLIS * 3 + 
                        DateUtils.SECOND_IN_MILLIS * 42;
    TextView mTextView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mTextView = (TextView) findViewById(R.id.empty);

        mCountDownTimer = new CountDownTimer(mInitialTime, 1000) {
            StringBuilder time = new StringBuilder();
            @Override
            public void onFinish() {
                mTextView.setText(DateUtils.formatElapsedTime(0));
                //mTextView.setText("Times Up!");
            }

            @Override
            public void onTick(long millisUntilFinished) {
                time.setLength(0);
                 // Use days if appropriate
                if(millisUntilFinished > DateUtils.DAY_IN_MILLIS) {
                    long count = millisUntilFinished / DateUtils.DAY_IN_MILLIS;
                    if(count > 1)
                        time.append(count).append(" days ");
                    else
                        time.append(count).append(" day ");

                    millisUntilFinished %= DateUtils.DAY_IN_MILLIS;
                }

                time.append(DateUtils.formatElapsedTime(Math.round(millisUntilFinished / 1000d)));
                mTextView.setText(time.toString());
            }
        }.start();
    }
}

答案 3 :(得分:1)

这也是科特林的一个例子

fun printDifferenceDateForHours() {

        val currentTime = Calendar.getInstance().time
        val endDateDay = "03/02/2020 21:00:00"
        val format1 = SimpleDateFormat("dd/MM/yyyy hh:mm:ss",Locale.getDefault())
        val endDate = format1.parse(endDateDay)

        //milliseconds
        var different = endDate.time - currentTime.time
        countDownTimer = object : CountDownTimer(different, 1000) {

            override fun onTick(millisUntilFinished: Long) {
                var diff = millisUntilFinished
                val secondsInMilli: Long = 1000
                val minutesInMilli = secondsInMilli * 60
                val hoursInMilli = minutesInMilli * 60
                val daysInMilli = hoursInMilli * 24

                val elapsedDays = diff / daysInMilli
                diff %= daysInMilli

                val elapsedHours = diff / hoursInMilli
                diff %= hoursInMilli

                val elapsedMinutes = diff / minutesInMilli
                diff %= minutesInMilli

                val elapsedSeconds = diff / secondsInMilli

                txt_timeleft.text = "$elapsedDays days $elapsedHours hs $elapsedMinutes min $elapsedSeconds sec"
            }

            override fun onFinish() {
                txt_timeleft.text = "done!"
            }
        }.start()
    }

答案 4 :(得分:0)

看看这篇文章,我认为它会帮助你:How to check day in android?

使用java.util.Calendar类,我认为你应该能够弄清楚如何完成剩下的工作。

http://developer.android.com/reference/java/util/Date.html - 你可以使用getDate(),getHours(),getMinutes(),getSeconds()等等......希望有所帮助!

答案 5 :(得分:0)

此软件是使用纯代码还是AppInventor?这是编码资源。

这是一个资源: [http://w2davids.wordpress.com/simple-countdowntimer-example/][1]

第二个(本地)资源: Countdown Timer required on Android

答案 6 :(得分:0)

long startTime;

private void start_countdown_timer()
{
    SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss");
    formatter.setLenient(false);


    String endTime = "18.09.2017, 15:05:36";
    long milliseconds=0;

    final CountDownTimer mCountDownTimer;

    Date endDate;
    try {
        endDate = formatter.parse(endTime);
        milliseconds = endDate.getTime();

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    startTime = System.currentTimeMillis();


    mCountDownTimer = new CountDownTimer(milliseconds, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {

            startTime=startTime-1;
            Long serverUptimeSeconds =
                    (millisUntilFinished - startTime) / 1000;

            String daysLeft = String.format("%d", serverUptimeSeconds / 86400);
            //txtViewDays.setText(daysLeft);
            Log.d("daysLeft",daysLeft);

            String hoursLeft = String.format("%d", (serverUptimeSeconds % 86400) / 3600);
            //txtViewHours.setText(hoursLeft);
            Log.d("hoursLeft",hoursLeft);

            String minutesLeft = String.format("%d", ((serverUptimeSeconds % 86400) % 3600) / 60);
            //txtViewMinutes.setText(minutesLeft);
            Log.d("minutesLeft",minutesLeft);

            String secondsLeft = String.format("%d", ((serverUptimeSeconds % 86400) % 3600) % 60);
            //txtViewSecond.setText(secondsLeft);
            Log.d("secondsLeft",secondsLeft);


        }

        @Override
        public void onFinish() {

        }
    }.start();


}

答案 7 :(得分:0)

我已经阅读了您的问题,已经遇到了这个问题,因此我在不使用任何第三方库的情况下为其编写了自定义代码。

以下是代码:

public class CountDownTimerDaysActivity extends AppCompatActivity {

/*Views declaration*/
private TextView months_left,weeks_left,daysLeft,hrsLeft,minLeft,secLeft,endDate;
/*Handler Declaration*/
private Handler handler;
/*set End Time for timer */
private String endDateTime="2019-03-21 10:15:00";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /*inflate layout for activity*/
    setContentView(R.layout.activity_count_down_timer);
    /*invoke initView method  for views*/
    initView();
}
/*initView method for findviews by id*/
private void initView() {
    months_left = findViewById(R.id.months_left);
    weeks_left = findViewById(R.id.weeks_left);
    daysLeft = findViewById(R.id.days_left);
    hrsLeft = findViewById(R.id.hrs_left);
    minLeft = findViewById(R.id.min_left);
    secLeft = findViewById(R.id.sec_left);
    endDate = findViewById(R.id.end_date);
    endDate.setText(endDateTime);
    /*invoke countDownStart() method for start count down*/
    countDownStart();
}

/*countDownStart() method for start count down*/
public void countDownStart() {
    handler = new Handler();
    Runnable runnable = new Runnable() {
        @SuppressLint("SetTextI18n")
        @Override
        public void run() {
            handler.postDelayed(this, 1000);
            try {
                @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                // Please set date in  YYYY-MM-DD hh:mm:ss format
                /*parse endDateTime in future date*/
                Date futureDate = dateFormat.parse(endDateTime);
                Date currentDate = new Date();
                /*if current date is not comes after future date*/
                if (!currentDate.after(futureDate)) {
                    long diff = futureDate.getTime()
                            - currentDate.getTime();

                    long days = diff / (24 * 60 * 60 * 1000);
                    diff -= days *(24  *60 * 60  *1000);
                    long hours = diff / (60 * 60*  1000);
                    diff -= hours * (60*  60 * 1000);
                    long minutes = diff / (60 * 1000);
                    diff -= minutes * (60  *1000);
                    long seconds = diff / 1000;
                    @SuppressLint("DefaultLocale") String dayLeft = "" + String.format("%02d", days);
                    @SuppressLint("DefaultLocale") String hrLeft = "" + String.format("%02d", hours);
                    @SuppressLint("DefaultLocale") String minsLeft = "" + String.format("%02d", minutes);
                    @SuppressLint("DefaultLocale") String secondLeft = "" + String.format("%02d", seconds);
                    daysLeft.setText(dayLeft + "D: ");
                    hrsLeft.setText(hrLeft + "H: ");
                    minLeft.setText(minsLeft + "M: ");
                    secLeft.setText(secondLeft + "S");

                } else {
                    textViewGone();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    handler.postDelayed(runnable, 1000);
}
private void textViewGone() {
    months_left.setVisibility(View.GONE);
    weeks_left.setVisibility(View.GONE);
    daysLeft.setVisibility(View.GONE);
    hrsLeft.setVisibility(View.GONE);
    minLeft.setVisibility(View.GONE);
    secLeft.setVisibility(View.GONE);
}
}

希望它对您有用

相关问题