Android - running a method periodically using postDelayed() call

zolio picture zolio · Jun 1, 2012 · Viewed 164.8k times · Source

I have a situation in an Android app where I want to start a network activity (sending out some data) which should run every second. I achieve this as follows:

In the onCreate() I have the code:

tv = new TextView(this);
tv.postDelayed(sendData, 1000);

The sendData() function:

   Handler handler = new Handler();
   private Runnable sendData=new Runnable(){
    public void run(){
        try {
            //prepare and send the data here..
            handler.removeCallbacks(sendData);
            handler.postDelayed(sendData, 1000);    
        }
        catch (Exception e) {
            e.printStackTrace();
        }   
    }
};

The problem come in like this: When user presses the back buttons and app comes out (UI disappears) the sendData() function still gets executed which is what I want. Now when user re-starts the app, my onCreate() gets called again and I get sendData() invoked twice a second. It goes on like that. Every time user comes out and starts again, one more sendData() per second happens.

What am I doing wrong? Is it my new Handler() creating problem? What is the best way to handle this? I want one sendData() call per second until user quits the app (form application manager).

Answer

Saad Asad picture Saad Asad · Dec 26, 2013
final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        //Do something after 100ms
        Toast.makeText(c, "check", Toast.LENGTH_SHORT).show();  
        handler.postDelayed(this, 2000);
      }
    }, 1500);