How to perform an action after a Random Time Delay? - Android
So I'm making an app on "I'm not telling you"... :-)
Going to the problem :
final ToggleButton passTog = (ToggleButton) findViewById(R.id.onoff);
passTog.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
init = System.currentTimeMillis();
handler.post(updater);
}
});
Up above is a normal toggle button, I previously defined a handler, using
this I'm running a Runnable named updater...(For the following: "display"
is a textview)
final Runnable updater = new Runnable() {
@Override
public void run() {
if (passTog.isChecked()) {
now = System.currentTimeMillis();
time = now - init;
display.setText(time + " ms");
handler.postDelayed(this, 30);
}
}
};
And here's the runnable... The variable time, now, init ... are time
variables.
What I'm trying to do is (right now) I'm updating the textview with the
milliseconds passed since the Toggle button is pressed (see the if
statement)
EXPLAINATION of the above code
So, activity starts, click the toggle button, init variable gets a value
of the current time... Program goes to the runnable. Now , after double
checking that the button is infact in the "on" state... the system puts
the current time in "now" ... and we have the time variable as the
subtraction of the two. And that gets updated in the textview "display"
every 30 milliseconds. In the app you can see the textview pacing as time
passes. Works great.
That's that, and what I want is...
The activity starts, you press the button.. After a random time delay* say
between 2-10 seconds.... The textview should then start getting updated.
We press a button, nothing seemingly happens, Then after that random
delay... the textview bursts up, and starts churning out the current time
starting from 1ms, that is the above runnable should run after that random
time delay.
Seeing as in the matter is completely logical and not really technical- I
need to somehow introduce a non-fixed time delay before the runnable does
it's thing.
I think we may be able to do this in the runnable itself... we already
have the "time" variable.... Why not use that in a "if" statement.... and
then reset the time variable so that it seems to start from the start.
Heavy stuff, I just can't seem to get it right.
Any idea how we can do this ?
No comments:
Post a Comment