java - 使用enable ReceiveTimeout后读取流

标签 java gps readline

我目前正在开发一个Java项目,其目标之一是在 map 上显示用户的当前位置。代码完成后,我意识到用户有可能在应用程序仍在运行时拔掉 GPS 设备。在重新创建上述场景时,我发现应用程序永远卡在代码处:

detectedGPSPortBufferReader.readLine();

所以,我查阅了旧的 Java 文档,找到了 enableReceiveTimeout() 方法,一切都很完美。 (值为 30000,30 秒)

现在,我想到了另一种情况,其中用户可以重新插入设备。在这种情况下,我的客户会希望设备再次开始阅读。但不幸的是这并没有发生。

我正在和我的好友“The Good Old Java Docs”一起工作,并且希望你们中的任何一位极客大神能够指导我的旅程。

我的代码:

try {
    myGPSConnector.detectedGPSPort.enableReceiveTimeout(3000);

    if(myGPSConnector.detectedGPSPortBufferReader.readLine() != null)
    {   
        myGPSConnector.nmeaResponse = myGPSConnector.detectedGPSPortBufferReader.readLine();
        System.out.println(myGPSConnector.nmeaResponse);
    }
}
catch (Exception e)
{
    locationString = "GPS Device not detected.";
}

@derrabink:它可以是不同的流,因为我尝试在我的代码中使用以下扩展:

try {
    myGPSConnector.detectedGPSPort.enableReceiveTimeout(3000);

    if(myGPSConnector.detectedGPSPortBufferReader.readLine() != null)
    {   
        myGPSConnector.nmeaResponse = myGPSConnector.detectedGPSPortBufferReader.readLine();
        System.out.println(defaultGPSConnector.nmeaResponse);
    }
}
catch (Exception e) 
{
    locationString = "GPS Device not detected.";

    try {
        defaultGPSConnector.detectedGPSPort.enableReceiveTimeout(30);
        } 
        catch (UnsupportedCommOperationException e1) 
        {
            System.out.println("UnsupportedCommOperationException");
                        }

    try {
            locationString = defaultGPSConnector.detectedGPSPortBufferReader.readLine();
        }
    catch (IOException e1) 
        {
            System.out.println("IOException ");
        }

并且它总是打印IOException

最佳答案

我会将您的 if 更改为 while 语句:

while ( myGPSConnector.detectedGPSPortBufferReader.readLine() == null ) {
    // don't do anything. Will stay here until the client decides to plug it again.
}

myGPSConnector.nmeaResponse = myGPSConnector.detectedGPSPortBufferReader.readLine();
System.out.println(myGPSConnector.nmeaResponse);

编辑。

for (long stop=System.nanoTime()+TimeUnit.SECONDS.toNanos(30); stop>System.nanoTime();)
{

    //this loop will execute for exactly 30 seconds
    if ( myGPSConnector.detectedGPSPortBufferReader.readLine() != null ) 
    {
        myGPSConnector.nmeaResponse = myGPSConnector.
        detectedGPSPortBufferReader.readLine();
        System.out.println(myGPSConnector.nmeaResponse);
    }
}

所以,你有一个 30 秒的循环,如果在这期间没有什么可读的,那就意味着这个人有比玩 GPS 更好的事情要做。

这是我的方法。注意,可能不起作用。

关于java - 使用enable ReceiveTimeout后读取流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16416584/

相关文章:

javac 找不到符号构造函数服务

java - 抽象类的对象是匿名内部类吗?

java - 读取用户输入并打印行(如果重复)

python - 逐行读取文本文件并存储匹配 Python 中特定模式的变量

c++ - Readline:如何在双选项卡上列出所有自动完成匹配项?

java - 使用 AES-GCM 中的 AAD

java - 我需要在每个星期五显示一条 toast 消息

ionic-framework - 位置不可用电容器 ionic

java - 通过UDP接收实时GPS数据

android - 仅来自网络的 GPS 位置