Search code examples
javaandroidhandlertiming

Programatically reduce time interval in handler. Android


When you use the postDelayed function on a handler, a delayMillis variable is required to specify the time after which the handler runs. I want my handler to repeat indefinitely so I have nested two postDelayed functions.

    final int initialdt = 1000;
    final Handler handler = new Handler();
    final Runnable r = new Runnable() {

        public void run() {

            handler.postDelayed(this, initialdt);
        }
    };
    handler.postDelayed(r, initialdt);

However using this method, the time between the run() calls is fixed. Since the inner postDelayed requires a final integer as a parameter. I want to reduce the time between consecutive calls. Is there a way to do so?


Solution

  • This should do what you want.

        final int initialDt = 1000;
        final Handler handler = new Handler();
        final Runnable r = new Runnable() {
            int dt = initialDt;
            public void run() {
                dt -= 100;
                if (dt >= 0) {
                    handler.postDelayed(this, dt);
                }
            }
        };
        handler.postDelayed(r, initialDt);