简体   繁体   中英

Calculating time difference with start time and elapsed time

public static final long TIMEOUT = 60000;
public static final long SYSTEM_TIME = System.currentTimeMillis();

I have the TIMEOUT Value for my application set as 60000 and i have my system time. Now how would i know that 50 seconds has been elapsed and i need to show a message to the end-user.

if (TIMEOUT  - SYSTEM_TIME <= 10000) {
    Toast.makeText(getApplicationContext(), "10 Seconds Left", Toast.LENGTH_LONG).show();
    disconnectHandler.postDelayed(disconnectCallback, DISCONNECT_TIMEOUT);
}

如果您不需要在该线程中执行其他操作,则可以使用sleep(50000)

This is how to run a specific task one-shot:

new Timer().schedule(new TimerTask() {              
            @Override
            public void run() {
                // TODO
                ...
            }
        }, TIMEOUT);

The doc is here (as reported by jimpanzer)

Maybe that you can use something like this :

long startTime = SystemClock.elapsedRealtime();
// do what you want
long endTime = SystemClock.elapsedRealtime();
long ellapsedTime = endTime - startTime;
if (ellapsedTime>TIME_OUT) {
    // do stuff
}

Maybe I am wrong or just not had enough coffee yet, but Timeout is 60000, your System value is much more - all millis starting at the year 1970 (if I am not mistaken here as well). This means your result from TIMEOUT - SYSTEM_TIME is negative and therefor a negative number and therefor smaller than 10000. So your if-statement always runs.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM