Reputation: 830
I have initialized an int variable i = 0
. My code has an infinite while loop which is checked immediately when the activity starts. In this loop I need to perform certain tasks after some time interval (e.g. 3 seconds). My code is similar to this:
while(1){
if (System.currentTimeMillis() - learningTime > 3000) {
learningTime = System.currentTimeMillis();
i++;
}
}
Since System.currentTimeMillis() - learningTime > 3000
is true at the beginning of my program execution, i
will increment quickly to 1
and later increments will be made every 3 seconds.
How to force i
to increment from 0
to 1
in 3 seconds after the activity starts?
Upvotes: 0
Views: 625
Reputation: 14847
Assign to learningTime the System.currentTimeMillis() value so it's 0 > 3000
learningTime = System.currentTimeMillis()
And, anyway you will block the main thread with this code.
That can be an example of Handler
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run()
{
handler.postDelayed(this, 3000);
}
};
handler.postDelayed(runnable, 3000);
Handler class
Runnable
Handler postDelayed
Anyway, you don't need anymore learningTime
and i
(?)
Upvotes: 2
Reputation: 10095
You can use a handler to solve this problem so that you don't block the main thread. I'm not sure if this is the ideal implementation though:
private static final long INTERVAL = 3000;//3 seconds
private Handler handler;
protected void onCreate(Bundle b)
{
super(b);
handler = new Handler();
//post an action to execute after an INTERVAL has elapsed.
handler.postDelayed(new Runnable(){
public void run(){
//do your stuff
doYourStuff();
//post the event again until a stopCondition is met.
if(stopCondition==false){
handler.postDelayed(this,INTERVAL);
}
}
},INTERVAL);
}
Upvotes: 1
Reputation: 8480
As requested in the comments, here is an example of how to use a Handler to delay running some code until a certain amount of time has passed. Define a handler as a variable in your Activity:
Handler handler = new Handler();
Since that handler was created on the UI thread, anything you post to it will also run on the same thread. You can schedule code to run immediately or with a delay. For example:
handler.postDelayed(new Runnable()
{
public void run()
{
//Your code here
}
}, 3000); //Code will be scheduled to run on the UI thread afer 3 seconds
Upvotes: 0