简体   繁体   English

用开始时间和经过时间计算时差

[英]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. 我的应用程序的超时值设置为60000,并且我有系统时间。 Now how would i know that 50 seconds has been elapsed and i need to show a message to the end-user. 现在,我怎么知道已经过去了50 seconds ,我需要向最终用户显示一条消息。

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) 该文档在这里 (据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). 也许我错了或者只是还没有喝咖啡,但是Timeout是60000,您的System值要高得多-所有的毫秒数都始于1970年(如果我在这里也没记错的话)。 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. 这意味着您从TIMEOUT-SYSTEM_TIME得到的结果为负,因此为负数,因此小于10000。因此,if语句始终运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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