Skip to content Skip to sidebar Skip to footer

How Do I Make A Simple Timer In Java With A Button Click To Start/stop The Timer?

In android studio in the MainActivity in the onCreate i did: timerValueRecord = (TextView) findViewById(R.id.timerValueRecord); In strings.xml i added: Copy

You can use StartTimer() and StopTimer() function where you want to start or stop the timer:

Solution 2:

try this way

publicclassAndroidTimerTaskExampleextendsActivity {



        Timer timer;

        TimerTask timerTask;



        //we are going to use a handler to be able to run in our TimerTaskfinalHandlerhandler=newHandler();



        @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

        }



        @OverrideprotectedvoidonResume() {

            super.onResume();



            //onResume we start our timer so it can start when the app comes from the background

            startTimer();

        }



        publicvoidstartTimer() {

            //set a new Timer

            timer = newTimer();



            //initialize the TimerTask's job

            initializeTimerTask();



            //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms

            timer.schedule(timerTask, 5000, 10000); //

        }



        publicvoidstoptimertask(View v) {

            //stop the timer, if it's not already nullif (timer != null) {

                timer.cancel();

                timer = null;

            }

        }



        publicvoidinitializeTimerTask() {



            timerTask = newTimerTask() {

                publicvoidrun() {



                    //use a handler to run a toast that shows the current timestamp

                    handler.post(newRunnable() {

                        publicvoidrun() {

                            //get the current timeStampCalendarcalendar= Calendar.getInstance();

                            SimpleDateFormatsimpleDateFormat=newSimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");

                            finalStringstrDate= simpleDateFormat.format(calendar.getTime());



                            //show the toastintduration= Toast.LENGTH_SHORT;  

                            Toasttoast= Toast.makeText(getApplicationContext(), strDate, duration);

                            toast.show();

                        }

                    });

                }

            };

        }

    }

Post a Comment for "How Do I Make A Simple Timer In Java With A Button Click To Start/stop The Timer?"