2011-04-24 101 views
3

我已經使用現在經典的Google藍牙聊天代碼實現了藍牙連接。但是,我有一個問題,我似乎無法把我的大腦包圍起來。如何檢測Android藍牙文件傳輸的EOF?

輸入流的閱讀是這樣的:

public void run() { 
    byte[] buffer = new byte[1024]; // buffer store for the stream 
    int bytes; // bytes returned from read() 

    // Keep listening to the InputStream until an exception occurs 
    while (true) { 
     try { 
      // Read from the InputStream 
      bytes = mmInStream.read(buffer); 
      // Send the obtained bytes to the UI Activity 
      mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) 
        .sendToTarget(); 
     } catch (IOException e) { 
      break; 
     } 
    } 
} 

現在,這很好,如果我只是打印出我收到了作爲最初的例子的字符。但是,假設我想要傳輸圖像文件。我不知道文件的大小,所以我不能計算收到的字節或類似的東西。在我的測試中,我似乎從輸入流中看不到「-1」,這似乎是從輸入流中讀取的「標準」。那麼我怎麼知道我已經到達了正在發送的文件的末尾?

謝謝你的幫助和你的時間。

回答

2

看來Android的藍牙輸入流永遠不會返回-1。

我想通過首先發送文件大小來設置一個簡單的協議,最後EOF信號會有所幫助。

+0

我在想,可能是這樣,但我想看看是否有我可以俯瞰簡單的方法。但是你已經證實我必須做的......謝謝! – 2011-04-24 13:42:51

1

嘗試

while ((bytes = mmInStream.read(buffer) != -1) 

,看看有沒有什麼幫助。

2

不,它不。據我所知,Android僅在Socket關閉時才發送-1。所以一個解決方法可能是做一個重新連接,但我試了幾個小時,並沒有得到它的工作,因爲我不明白這個「特殊」的代碼在這裏(從Stackoverflow線程複製)設置套接字:

 BluetoothSocket tmp = null; 
    Log.d(TAG, "New Connection initialized"); 
    Method m; 
    try { 
     m = device.getClass().getMethod("createRfcommSocket", 
       new Class[] { int.class }); 
     tmp = (BluetoothSocket) m.invoke(device, 1); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    mmSocket = tmp; 

只有當我的應用程序啓動第一個文件傳輸時,此套接字才起作用。如果我想用一個全新的實例化對象(以及用該代碼創建的一個新的套接字)「重新連接」,程序會凍結阻塞方法mmSocket.connect()。看起來方法似乎永遠不會結束。這是推動我堅果...

1

試試這個:

 public void run() { 
     byte[] buffer; 
     ArrayList<Integer> arr_byte = new ArrayList<Integer>(); 
     while (true) { 
      try { 
       int data = mmInStream.read(); 
       if(mmInStream.available()>0) { 
        arr_byte.add(data); 
       } else { 
        arr_byte.add(data); 
        buffer = new byte[arr_byte.size()]; 
        for(int i = 0 ; i < arr_byte.size() ; i++) { 
         buffer[i] = arr_byte.get(i).byteValue(); 
        } 
        Log.e("INPUT",new String(buffer)); 
        mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) 
          .sendToTarget(); 
        arr_byte = new ArrayList<Integer>(); 
       } 
      } catch (IOException e) { 
       break; 
      } 
     } 
    }