Search code examples
androidmultithreadingtimer

Run a timer infinitely until button pressed?


How can I add timed functionality that doesn't end unless the button is clicked again? This runs a thread okay but it won't restart unless I go to another tab in the app and go back to it.

 metroStartBtn.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            metronomeOn = !metronomeOn;

            if(metronomeOn)
            {
                final Thread t = new Thread(new Runnable()
                {

                    @Override
                    public void run()
                    {
                        while(!toExit){
                            // Your code
                            try {
                                playSound(getContext(), 1);
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });

                    t.start();

            }

            else
            {
                toExit = true;
            }

        }

    });

Solution

  • Because after the first run , toExit is true therefore your while loop will not execute after that

    metroStartBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                metronomeOn = !metronomeOn;
    
                if(metronomeOn)
                {
                    final Thread t = new Thread(new Runnable()
                    {
    
                        @Override
                        public void run()
                        {
                            while(metronomeOn){
                                // Your code
                                try {
                                    playSound(getContext(), 1);
                                    Thread.sleep(100);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
    
                    t.start();
    
                }
            }
    
        });