Kafros
Kafros

Reputation: 176

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?

Upvotes: 0

Views: 1951

Answers (2)

giannisf
giannisf

Reputation: 2599

You could set the limit inside postDelayed

final Handler handler = new Handler();

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                handler.postDelayed(this, limit);
            }
        }, 1000);

Upvotes: 0

Mikael Ohlson
Mikael Ohlson

Reputation: 3264

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);

Upvotes: 3

Related Questions