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

public class AndroidTimerTaskExample extends Activity {



        Timer timer;

        TimerTask timerTask;



        //we are going to use a handler to be able to run in our TimerTask

        final Handler handler = new Handler();



        @Override

        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

        }



        @Override

        protected void onResume() {

            super.onResume();



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

            startTimer();

        }



        public void startTimer() {

            //set a new Timer

            timer = new Timer();



            //initialize the TimerTask's job

            initializeTimerTask();



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

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

        }



        public void stoptimertask(View v) {

            //stop the timer, if it's not already null

            if (timer != null) {

                timer.cancel();

                timer = null;

            }

        }



        public void initializeTimerTask() {



            timerTask = new TimerTask() {

                public void run() {



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

                    handler.post(new Runnable() {

                        public void run() {

                            //get the current timeStamp

                            Calendar calendar = Calendar.getInstance();

                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");

                            final String strDate = simpleDateFormat.format(calendar.getTime());



                            //show the toast

                            int duration = Toast.LENGTH_SHORT;  

                            Toast toast = 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?"