web-dev-qa-db-ja.com

Androidでカウントダウンタイマーを作るには?

XMLには2つのEditTextがあります。あるEditTextでは、ユーザーは分として数値を入力し、別のEditTextでは秒として数値を入力できます。終了ボタンをクリックすると、秒数EditTextが1秒ごとにカウントダウンとテキストの更新を開始します。

また、0分0秒になるまで更新を続けるにはどうすればよいですか。

143
Sabbir Ahmed
new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
       //here you can have your logic to set text to edittext
    }

    public void onFinish() {
        mTextField.setText("done!");
    }

}.start();

これを参照してください link

341
Shankar Agarwal

あなたが以下のコードを使うならば(受け入れられた答えで述べられるように)、

new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
       //here you can have your logic to set text to edittext
    }

    public void onFinish() {
        mTextField.setText("done!");
    }

}.start();

参照を慎重にクリーンアップしないと、このコードを使用するアクティビティのインスタンスのメモリリークが発生します。

次のコードを使う

//Declare timer
CountDownTimer cTimer = null;

//start timer function
void startTimer() {
    cTimer = new CountDownTimer(30000, 1000) {
        public void onTick(long millisUntilFinished) {
        }
        public void onFinish() {
        }
    };
    cTimer.start();
}


//cancel timer
void cancelTimer() {
    if(cTimer!=null)
        cTimer.cancel();
}

所有するActivity/FragmentのonDestroy()/ onDestroyView()が呼び出されるたびに、cTtimer.cancel()を呼び出す必要があります。

57
shanraisshan

enter image description here

MainActivity.Java

package com.zeustechnocrats.countdown;

import Android.os.Bundle;
import Android.os.Handler;
import Android.support.v7.app.AppCompatActivity;
import Android.view.View;
import Android.widget.LinearLayout;
import Android.widget.TextView;

import Java.text.SimpleDateFormat;
import Java.util.Date;

public class MainActivity extends AppCompatActivity {

    private String EVENT_DATE_TIME = "2019-12-31 10:30:00";
    private String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private LinearLayout linear_layout_1, linear_layout_2;
    private TextView tv_days, tv_hour, tv_minute, tv_second;
    private Handler handler = new Handler();
    private Runnable runnable;

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

        initUI();
        countDownStart();
    }

    private void initUI() {
        linear_layout_1 = findViewById(R.id.linear_layout_1);
        linear_layout_2 = findViewById(R.id.linear_layout_2);
        tv_days = findViewById(R.id.tv_days);
        tv_hour = findViewById(R.id.tv_hour);
        tv_minute = findViewById(R.id.tv_minute);
        tv_second = findViewById(R.id.tv_second);
    }

    private void countDownStart() {
        runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    handler.postDelayed(this, 1000);
                    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
                    Date event_date = dateFormat.parse(EVENT_DATE_TIME);
                    Date current_date = new Date();
                    if (!current_date.after(event_date)) {
                        long diff = event_date.getTime() - current_date.getTime();
                        long Days = diff / (24 * 60 * 60 * 1000);
                        long Hours = diff / (60 * 60 * 1000) % 24;
                        long Minutes = diff / (60 * 1000) % 60;
                        long Seconds = diff / 1000 % 60;
                        //
                        tv_days.setText(String.format("%02d", Days));
                        tv_hour.setText(String.format("%02d", Hours));
                        tv_minute.setText(String.format("%02d", Minutes));
                        tv_second.setText(String.format("%02d", Seconds));
                    } else {
                        linear_layout_1.setVisibility(View.VISIBLE);
                        linear_layout_2.setVisibility(View.GONE);
                        handler.removeCallbacks(runnable);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        handler.postDelayed(runnable, 0);
    }

    protected void onStop() {
        super.onStop();
        handler.removeCallbacks(runnable);
    }
}

activity_main.xml

    <LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    Android:background="@Android:color/white"
    Android:orientation="horizontal">

    <LinearLayout
        Android:id="@+id/linear_layout_1"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:background="@Android:color/black"
        Android:gravity="center_horizontal"
        Android:visibility="gone">

        <TextView
            Android:id="@+id/tv_event"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:layout_margin="20dp"
            Android:text="Android Event Start"
            Android:textColor="@Android:color/white"
            Android:textSize="20dp"
            Android:textStyle="normal" />
    </LinearLayout>

    <LinearLayout
        Android:id="@+id/linear_layout_2"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:background="@Android:color/black"
        Android:visibility="visible">

        <LinearLayout
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:layout_weight="1"
            Android:orientation="vertical">

            <TextView
                Android:id="@+id/tv_days"
                Android:layout_width="wrap_content"
                Android:layout_height="wrap_content"
                Android:layout_gravity="center"
                Android:text="00"
                Android:textColor="@Android:color/white"
                Android:textSize="20dp"
                Android:textStyle="bold" />

            <TextView
                Android:id="@+id/tv_days_title"
                Android:layout_width="wrap_content"
                Android:layout_height="wrap_content"
                Android:layout_gravity="center"
                Android:text="Days"
                Android:textColor="@Android:color/white"
                Android:textSize="20dp"
                Android:textStyle="normal" />
        </LinearLayout>

        <LinearLayout
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:layout_weight="1"
            Android:orientation="vertical">

            <TextView
                Android:id="@+id/tv_hour"
                Android:layout_width="wrap_content"
                Android:layout_height="wrap_content"
                Android:layout_gravity="center"
                Android:text="00"
                Android:textColor="@Android:color/white"
                Android:textSize="20dp"
                Android:textStyle="bold" />

            <TextView
                Android:id="@+id/tv_hour_title"
                Android:layout_width="wrap_content"
                Android:layout_height="wrap_content"
                Android:layout_gravity="center"
                Android:text="Hour"
                Android:textColor="@Android:color/white"
                Android:textSize="20dp"
                Android:textStyle="normal" />
        </LinearLayout>

        <LinearLayout
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:layout_weight="1"
            Android:orientation="vertical">

            <TextView
                Android:id="@+id/tv_minute"
                Android:layout_width="wrap_content"
                Android:layout_height="wrap_content"
                Android:layout_gravity="center"
                Android:text="00"
                Android:textColor="@Android:color/white"
                Android:textSize="20dp"
                Android:textStyle="bold" />

            <TextView
                Android:id="@+id/tv_minute_title"
                Android:layout_width="wrap_content"
                Android:layout_height="wrap_content"
                Android:layout_gravity="center"
                Android:text="Minute"
                Android:textColor="@Android:color/white"
                Android:textSize="20dp"
                Android:textStyle="normal" />
        </LinearLayout>

        <LinearLayout
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:layout_weight="1"
            Android:orientation="vertical">

            <TextView
                Android:id="@+id/tv_second"
                Android:layout_width="wrap_content"
                Android:layout_height="wrap_content"
                Android:layout_gravity="center"
                Android:text="00"
                Android:textColor="@Android:color/white"
                Android:textSize="20dp"
                Android:textStyle="bold" />

            <TextView
                Android:id="@+id/tv_second_title"
                Android:layout_width="wrap_content"
                Android:layout_height="wrap_content"
                Android:layout_gravity="center"
                Android:text="Second"
                Android:textColor="@Android:color/white"
                Android:textSize="20dp"
                Android:textStyle="normal" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
46

次のコードをコピーして貼り付けてください........

MainActivity

パッケージcom.example.countdowntimer;

import Java.util.concurrent.TimeUnit;
import Android.app.Activity;
import Android.os.Bundle;
import Android.os.CountDownTimer;
import Android.widget.TextView;


public class MainActivity extends Activity {


      TextView text1;

 private static final String FORMAT = "%02d:%02d:%02d";

 int seconds , minutes;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    text1=(TextView)findViewById(R.id.textView1);

    new CountDownTimer(16069000, 1000) { // adjust the milli seconds here

        public void onTick(long millisUntilFinished) {

            text1.setText(""+String.format(FORMAT,
                    TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
                    TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
  TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
                      TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));              
        }

        public void onFinish() {
            text1.setText("done!");
        }
     }.start();             

  }

  }

activity_main.xml

 <RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
 Android:layout_width="match_parent"
 Android:layout_height="match_parent"
 Android:orientation="vertical" >

<TextView
    Android:id="@+id/textView1"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:layout_alignParentLeft="true"
    Android:layout_alignParentTop="true"
    Android:layout_marginLeft="34dp"
    Android:layout_marginTop="58dp"
    Android:text="Large Text"
    Android:textAppearance="?android:attr/textAppearanceMedium" />

   </RelativeLayout>
37
gAuRaV jAiN

秒とtextviewオブジェクトを渡して、以下の関数を呼び出すだけ

public void reverseTimer(int Seconds,final TextView tv){

    new CountDownTimer(Seconds* 1000+1000, 1000) {

        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;
            tv.setText("TIME : " + String.format("%02d", minutes)
                    + ":" + String.format("%02d", seconds));
        }

        public void onFinish() {
            tv.setText("Completed");
        }
    }.start();
}

時間、分、秒のカウントダウンタイマーを反転します。

public void reverseTimer(int Seconds, final TextView tv) {

    new CountDownTimer(Seconds * 1000 + 1000, 1000) {

        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000);

            int hours = seconds / (60 * 60);
            int tempMint = (seconds - (hours * 60 * 60));
            int minutes = tempMint / 60;
            seconds = tempMint - (minutes * 60);

            tv.setText("TIME : " + String.format("%02d", hours)
                    + ":" + String.format("%02d", minutes)
                    + ":" + String.format("%02d", seconds));
        }

        public void onFinish() {
            tv.setText("Completed");
        }
    }.start();
}
8
tej shah

Kotlinを使う:

var timer = object: CountDownTimer(30000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            tvTimer.setText("seconds remaining: " + millisUntilFinished / 1000)
        }

        override fun onFinish() {
            tvTimer.setText("done!")
        }
    }
timer.start()
2

この方法を試してください:

private void startTimer() {
    startTimer = new CountDownTimer(30000, 1000) {

        public void onTick(long millisUntilFinished) {

            long sec = (TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
 TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));

            Log.e(TAG, "onTick: "+sec );
            tv_timer.setText(String.format("( %02d SEC )", sec));
            if(sec == 1)
            {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tv_timer.setText("( 00 SEC )");
                    }
                }, 1000);
            }


        }

        public void onFinish() {
            tv_timer.setText("Timer finish");
        }
    }.start();
}
1
V.Y.

インターフェースのやり方.

import Android.os.CountDownTimer;

/**
 * Created by saikiran on 07-03-2016.
 */
public class CountDownTimerCustom extends CountDownTimer {

    private TimeTickListener mTickListener;
    private TimeFinishListener mFinishListener;
    private long millisUntilFinished;

    public CountDownTimerCustom(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);

    }

    public void updateTickAndFinishListener(TimeTickListener tickListener) {
        mTickListener = tickListener;
    }

    public void updateFinishListner(TimeFinishListener listener) {
        mFinishListener = listener;
    }

    public long getCurrentMs() {
        return millisUntilFinished;
    }

    public int getCurrentSec() {
        return (int) millisUntilFinished / 1000;
    }

    @Override
    public void onTick(long millisUntilFinished) {
        this.millisUntilFinished = millisUntilFinished;
        if (mTickListener != null)
            mTickListener.onTick(millisUntilFinished);
    }

    @Override
    public void onFinish() {
        if (mTickListener != null)
            mTickListener.onFinished();
        mFinishListener.onFinished();
    }


    public interface TimeTickListener {
        void onTick(long mMillisUntilFinished);

        void onFinished();
    }

    public interface TimeFinishListener {
        void onFinished();
    }
}
0
Sai Kiran
 var futureMinDate = Date()
    val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)
    try {
        futureMinDate = sdf.parse("2019-08-22")
    } catch (e: ParseException) {
        e.printStackTrace()
    }

    // Here futureMinDate.time Returns the number of milliseconds since January 1, 1970, 00:00:00 GM
    // So we need to subtract the millis from current millis to get actual millis
    object : CountDownTimer(futureMinDate.time - System.currentTimeMillis(), 1000) {
        override fun onTick(millisUntilFinished: Long) {
            val sec = (millisUntilFinished / 1000) % 60
            val min = (millisUntilFinished / (1000 * 60)) % 60
            val hr = (millisUntilFinished / (1000 * 60 * 60)) % 24
            val day = ((millisUntilFinished / (1000 * 60 * 60)) / 24).toInt()
            val formattedTimeStr = if (day > 1) "$day days $hr : $min : $sec"
            else "$day day $hr : $min : $sec"
            tvFlashDealCountDownTime.text = formattedTimeStr
        }

        override fun onFinish() {
            tvFlashDealCountDownTime.text = "Done!"
        }
    }.start()

将来の日付を渡し、ミリ秒に変換します。

それは魅力のように機能します。

0
Shaon

これが私がKotlinで使った解決策です

private fun startTimer()
{
    Log.d(TAG, ":startTimer: timeString = '$timeString'")

    object : CountDownTimer(TASK_SWITCH_TIMER, 250)
    {
        override fun onTick(millisUntilFinished: Long)
        {
            val secondsUntilFinished : Long = 
            Math.ceil(millisUntilFinished.toDouble()/1000).toLong()
            val timeString = "${TimeUnit.SECONDS.toMinutes(secondsUntilFinished)}:" +
                    "%02d".format(TimeUnit.SECONDS.toSeconds(secondsUntilFinished))
            Log.d(TAG, ":startTimer::CountDownTimer:millisUntilFinished = $ttlseconds")
            Log.d(TAG, ":startTimer::CountDownTimer:millisUntilFinished = $millisUntilFinished")
        }

        @SuppressLint("SetTextI18n")
        override fun onFinish()
        {
            timerTxtVw.text = "0:00"
            gameStartEndVisibility(true)
        }
    }.start()
}
0
deepGrave
public class Scan extends AppCompatActivity {
int minute;
long min;
TextView tv_timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan2);
    tv_timer=findViewById(R.id.tv_timer);
    minute=Integer.parseInt("Your time in string form like 10");
    min= minute*60*1000;
    counter(min);
}
private void counter(long min) {
    CountDownTimer timer = new CountDownTimer(min, 1000) {
        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000) % 60;
            int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
            int hours = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
            tv_timer.setText(String.format("%d:%d:%d", hours, minutes, seconds));
        }
        public void onFinish() {
            Toast.makeText(getApplicationContext(), "Your time has been completed",
                    Toast.LENGTH_LONG).show();
        }
    };
    timer.start();
}

}