Search code examples
androidrunnable

Twice repetition in run()


I expect that the following code block writes "Hello!" once per second. But it writes it twice. What am I doing wrong?

    handler = new Handler();
    final Runnable r = new Runnable() {
        public void run() {
            Log.d("message", "Hello!");             
            handler.postDelayed(this, 1000);
        }
    };

    handler.postDelayed(r, 1000);
    runOnUiThread(r);

Solution

  • it writes it twice because you are posting it twice in the UI thread queue. One with the handler, the other with the runnable.

    handler.postDelayed(r, 1000);
    runOnUiThread(r);
    

    Accordingly with your requirements get rid of one the two. To me it looks like you want just the handler