0

Here I am doing it using Handler but it only increments a number once. I want it to increment the number until I stop it using handler.removeCallbacksAndMessages(null);.

Can anyone please guide me how can I achieve this. I am just new to android.

   Handler handler;
handler = new Handler();
 handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        count++;

                    }
                }, 1000);
Wasif
  • 61
  • 10

3 Answers3

0

try this

Handler handler;
handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
         count++;
         handler.postDelayed(this, 1000);
    }
}, 1000);
Priyanka
  • 3,369
  • 1
  • 10
  • 33
0

You can

  • rerun the runnable every second
  • use AlarmManager.

I'd suggest you to check out this link to get deeper understanding on multiple ways how to implement the post delayed or alarm manager to repeat a task every X seconds.

EDIT: I'd suggest you to stop the handler in onPause method.

isaaaaame
  • 460
  • 4
  • 9
0

Define a Thread a start it.

   Thread counterThread=new Thread(()->{
            try{
                while(true){
                counter++;
                Thread.sleep(1000);
                }
            }
            catch (Exception e){

            }
        });
    counterThread.start();

And when you want to stop this thread call counterThread.interrupt();

Ankit Dubey
  • 1,000
  • 1
  • 8
  • 12