Reputation: 876
I would like to do something like that:
@Override
protected String doInBackground(Object... params) {
int i = 0;
int max = Integer.MAX_VALUE;
GPSTracker gps = new GPSTracker(context);
do
{
//Something
} while(10 seconds);
return null;
}
How do put a count time in a while statemente. I would like to make this in 10 seconds.
Upvotes: 0
Views: 125
Reputation: 876
I did it:
long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end)
{
// run
}
Thank you for all the answers.
Upvotes: 0
Reputation: 645
You can use Thread.sleep(); (Not very clean).
Better use a Handler to do this.
Ex:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// You code here
}
}, 775); // Time in millis
Upvotes: 0
Reputation: 3699
A handy alternative to
Thread.sleep(timeInMillis)
is
TimeUnit.SECONDS.sleep(10)
Then the units are more explicit and easier to reason about.
Note that both these methods throw InterruptedException, which you will have to deal with. You can learn more about that here. If, as is often the case, you don't want to use interrupts, and you don't want your code to be cluttered with try/catch blocks, Google Guava's Uninterruptibles can be handy:
Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS);
Upvotes: 0
Reputation: 28619
To delay execution, you can sleep
a thread:
Thread.sleep(timeInMills);
This line may throw a thread exception, and it should never be executed on the main UI thread, as it will cause the app to halt communication with Android, causing a ANR
.
To run processes in the background of a single activity, you should spawn a new Thread
.
new Thread(){
public void run(){
//Process Stuff
}
}.start();
If you would like to have this section of code run throughout the entire life of your application, including when it is hidden to the user, you should look into running a service for long lived tasks.
Upvotes: 2
Reputation: 77196
If you're wanting to run a task periodically, use Timer#scheduleAtFixedRate
.
Upvotes: 2