How to execute some piece of code after a certain number of seconds? In particular, I want a method that displays interstitial ads to display 10 seconds after the activation is opened.
3 answers
Do not write bikes please
All have come up for you
new Timer().schedule(new TimerTask() {...}, 10000); - Keep in mind, in this case a separate thread will be created in which the code will run. That is, for example, you cannot directly access UI elements from there. - eugeneek
- All the same, the option via
Handlermore preferable (for Android of course) - Barmaley
|
Another option:
new Handler().postDelayed(new Runnable() {...}, 10000); Do the same in MainThread (UIThread) from any background thread:
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {...}, 10000); |
Like that:
class Retarder implements Runnable { private long retard; public Retarder(long retard) { this.retard=retard; } @Override public void run() { try { Thread.sleep(retard); } catch (InterruptedException e) { Log.i(TAG, "Interrupted retard"); } //выполняем код здесь } } Call this:
new Thread(new Retarder(10000)).start(); - 2Why it was impossible to use the standard implementation? new Timer (). schedule (new TimerTask () {...}, 10000); - mifkamaz
- Million options and a small cart on top, I would like to use the old school version :) - Barmaley
- @mifkamaz why did you decide that it was your standard implementation? This is just one of the ways that is not suitable for all cases.
Timercreates a new background thread in whichTimerTaskwill run. Thus, it cannot directly handle UI elements. So you were quick to call this method standard. - eugeneek - Well, in general, yes)) The taste and color of all markers are different - mifkamaz
|