I Want to Execute Code Every X Seconds, But Handler.Postdelayed Not Working

Handler postDelayed - print every second something

Working answer:

int t = 0;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
t++;
textView.setText(getString(R.string.formatted_time, t));
if(t<10) {
handler.postDelayed(this, 1000);
}
}
}, 1000);

Where formatted_time is something like that:

<string android:name="formatted_time">%d seconds</string>

I am using handler for delay in android but it's not working

You are using postDelayed incorrectly. It looks like you expect it to work the same way Thread.sleep would work. However that is not the case.

Here is a correct implementation of what you are trying to achieve:

private Handler handler = new Handler();
private TextView textView;

private int i = 0;
private boolean flip;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.hello);
handler.post(hello_first);
}

private Runnable hello_first = new Runnable() {
@Override
public void run() {
if(++i == 5) {
handler.removeCallbacks(this);
return;
}

if(flip) {
textView.setText("Nice Work");
} else {
textView.setText("Hello");
}
flip = !flip;

handler.postDelayed(this, TimeUnit.SECONDS.toMillis(2));
}
};

Android postDelayed does not delay

When you call postDelayed(), it just places the Runnable in a queue and returns immediately. It does not wait for the runnable to be executed.

If you need something to happen after a delay, put the code in the run() method of the runnable.

How to call a method after a delay in Android

Kotlin

Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
}, 100)

Java

final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);


Related Topics



Leave a reply



Submit