2012-08-09 83 views
1

我试图从输入流中读取数据,但如果程序没有接收到X数据量的时间,我想终止尝试并返回-1。我以前使用Thread.sleep(X),但后来意识到这是一个完全不正确的做法。如果有人有任何想法,请让我知道。这里是我的代码从输入流中读取...等待只输入X时间的输入

  try { 
       // Read from the InputStream 
       bytes = mmInStream.read(buffer, 0, length); 

       // Send the obtained bytes to the UI Activity 
       mHandler.obtainMessage(MainMenu.MESSAGE_READ, bytes, -1, buffer) 
         .sendToTarget(); 
      } catch (IOException e) { 
       Log.e(TAG, "disconnected", e); 
       connectionLost(); 
       // Start the service over to restart listening mode 
       BluetoothService.this.start(); 
       //break; 
      } 

回答

1

您可以使用Future来做到这一点。

首先,你需要将返回为“未来”价值的一类:

public class ReadResult { 
    public final int size; 
    public final byte[] buffer; 

    public ReadResult(int size, byte[] buffer) { 
     this.size = size; 
     this.buffer = buffer; 
    } 
} 

然后,你需要使用执行服务,并使用get(long timeout, TimeUnit unit)这样的:

 ExecutorService service = Executors.newSingleThreadExecutor(); 
     Future<ReadResult> future = service.submit(new Callable<ReadResult>() { 

      @Override 
      public ReadResult call() throws Exception { 
       bytes = mInStream.read(buffer, 0, length); 
       return new ReadResult(bytes, buffer); 
      } 
     }); 

     ReadResult result = null; 
     try { 
      result = future.get(10, TimeUnit.SECONDS); 
     } catch (InterruptedException e1) { 
      // Thread was interrupted 
      e1.printStackTrace(); 
     } catch (ExecutionException e1) { 
      // Something bad happened during reading 
      e1.printStackTrace(); 
     } catch (TimeoutException e1) { 
      // read timeout 
      e1.printStackTrace(); 
     } 

     if (result != null) { 
      // here you can use it 
     } 

以这种方式你将能够实现你的目标。 Plz指出它最好继承Callable类,它将接受inputstream作为构造函数参数,然后使用类变量。

0

您可以开始一个新的线程,并在那里等待x时间量。通过对您的活动的引用,一旦时间结束,您可以从时间线程中调用您的活动中的方法。

例如。

Thread time = new Thread() { 

Activity foo; 

public addActivity(Activity foo) { 
this.foo = foo; 
} 

public void run() { 
Thread.sleep(x); 
// Once done call method in activity 
foo.theTimeHasCome(); 
} 

}.start(); 

我希望这有助于!

+0

我不确定这会起作用,它似乎与使用'Thread.sleep()'类似。我想调用'mmInStream.read()',如果在'InStream'获得一个字节之前经过了'X时间量',我想返回'-1'的值。 – JuiCe 2012-08-09 16:43:44