2012-08-09 82 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