public void start(final int timeInMS){
AsyncTask<Void, Void, Void> timer = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
long timeWhenStart = System.nanoTime();
long now;
do {
now = System.nanoTime();
} while ((now - timeWhenStart) < (timeInMS * 1000000));
System.out.println((now - timeWhenStart) < (timeInMS * 1000000));
return null;
}
@Override
protected void onPostExecute(Void result) {
IntensityArc.this.setVisibility(View.INVISIBLE);
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
timer.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
} else {
timer.execute((Void[]) null);
}
}
The output of this code is : false
The program should jump out of the loop when the condition is not satisfied. But the value of (now - timeWhenStart)
was around 1,400,000,000 while the value of (timeInMS * 1000000)
was 10,000,000,000, when the program stopped. The condition is obviously still satisfied. How can this be?
I use this timer to make the custom view disappear when time runs out.
PS I tried this time to make a class that extends the AsyncTask
class, so it is no longer anonymous. And this time it worked. I don't understand why.
Your cycle repeat while the condition is true . So the cycle ends when the condition is false and your print it.
EDIT after updated question:
timeInMS is int, max value of int is 2 147 483 647. If time timeInMS is 10 000, than 10 000 * 1 000 000 is more than a max value of the int. As it doesn't fit into 32 bit, result int is 1 410 065 408.
You can make it long by multiplying long value.
long timeInNs = timeInMS * 1000000L;
Use long data type instead of all integer values. If using numaric value then use like : 100000L
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.