how to create a countdown timer in android using t

2020-05-08 09:13发布

问题:

i have an android activity that display the difference between 2 dates but what i want is to display the difference in count down time i tried this code but it do not display anything.

can anyone help me to fix this problem ???

firstActivity.java

package com.devleb.expandablelistdemo3;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class FirstActivity extends Activity {

    long diffSeconds;
    long diffMinutes;
    long diffHours;
    long diffDays;


    private Handler handler;
    private boolean Running = true;

    Date d1; 
    Date d2 = null;
    SimpleDateFormat format;

    String dateStop = "06/12/2014 23:00:00";

    // private DatabaseHelper dbHelper = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        getDiffDate();


    }

    public void listTeams(View v) {
        Intent in = new Intent(getBaseContext(), MainActivity.class);
        startActivity(in);
    }

    public void listGroups(View v) {
        Intent in = new Intent(getBaseContext(), GroupList.class);
        startActivity(in);
    }

    public void DisplaySched(View v) {

        Intent in = new Intent(getBaseContext(), MatchScheduleList.class);
        startActivity(in);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.first, menu);
        return true;
    }

    public void getDiffDate() {



        // HH converts hour in 24 hours format (0-23), day calculation
        format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

        d1 = new Date();

        d2 = null;

        handler = new Handler();




        Runnable runnable = new Runnable() {


            @Override
            public void run() {
                // TODO Auto-generated method stub
            while(Running){
                try{

                    d2 = format.parse(dateStop);

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

                     diffSeconds = diff / 1000 % 60;
                     diffMinutes = diff / (60 * 1000) % 60;
                     diffHours = diff / (60 * 60 * 1000) % 24;
                     diffDays = diff / (24 * 60 * 60 * 1000);

                    System.out.print(diffDays + " days, ");
                    System.out.print(diffHours + " hours, ");
                    System.out.print(diffMinutes + " minutes, ");
                    System.out.print(diffSeconds + " seconds.");


                    Thread.sleep(1000);//1 second
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        diffSeconds -= 1;

                        TextView txtDate = (TextView) findViewById(R.id.txtDifDate);
                        String resultDate = diffDays + "days " + diffHours + "Hours "
                                + diffMinutes + "Min " + diffSeconds + "S";
                        txtDate.setText(resultDate);
                    }
                });
            }
          }
        };



    }
}

回答1:

There are many ways, main thing to take notice is if you have to update the ui, you have to run on ui thread, if we do using CountDownTimer, this is way doing this

public class DateCountDownTimer extends CountDownTimer 
{

        public DateCountDownTimer(long startTime, long interval) 
        {
            super(startTime, interval);             
        }

        @Override
        public void onFinish() 
        {
            txvDate.setText("0 min 0 sec");
            this.cancel();
        }

        @Override
        public void onTick(long millisUntilFinished) 
        {
                 diffSeconds = millisUntilFinished / 1000 % 60;
                 diffMinutes = millisUntilFinished / (60 * 1000) % 60;
                 diffHours = millisUntilFinished / (60 * 60 * 1000) % 24;
                 diffDays = millisUntilFinished / (24 * 60 * 60 * 1000);
                 String resultDate = diffDays + "days " + diffHours + "Hours "
                            + diffMinutes + "Min " + diffSeconds + "S";
                 txtDate.setText(resultDate);
        }
    }

To start the timer, use this

     long diff = d2.getTime() - d1.getTime();
     long interval=1000;
     DateCountDownTimer timer=new DateCountDownTimer(diff,interval);
     timer.start();//start the timer

There are various other ways AsyncTask.

Please Do Accept Answer, If it helps!