2016-02-26 125 views
2

我有一個藍牙設備來讀取藍牙設備的任何數據。基本上我想我的應用程序連接到設備並接收它發送的數據。但是到目前爲止,我能夠連接到藍牙設備,但我無法從它接收任何輸入。無法在Android的

這裏是我的問題:

ⅰ)DataInputStream.available()始終返回0

ⅱ)如果我使用任何斷點線 字節= input.read(緩衝液); //這將凍結不顯示任何東西。 和它下面的線永遠不會執行

public class ConnectThread extends Thread{ 

    final String TAG="ConnectThread"; 
    private ReadThread mReadThread = null; 
    private final InputStream mmInStream; 
    private final OutputStream mmOutStream; 

    private boolean isDeviceConnected; 


    public final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 
    private BluetoothSocket mmSocket = null; 
    Handler mHandler; 
    BluetoothDevice bTdevice; 
    private DataInputStream mReadData = null; 



    public ConnectThread(BluetoothDevice bTdevice, Handler mHandler) { 
     super(); 
     this.bTdevice = bTdevice; 
     this.mHandler = mHandler; 

     InputStream tmpIn = null; 
     OutputStream tmpOut = null; 

     BluetoothSocket socket; 
     try { 
      socket = bTdevice.createRfcommSocketToServiceRecord(MY_UUID); 
      System.out.println("**** Socket created using standard way******"); 
      tmpIn = socket.getInputStream(); 
      tmpOut = socket.getOutputStream(); 
      mmSocket = socket; 


     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     mmInStream = tmpIn; 
     mmOutStream = tmpOut; 
    } 

    @Override 
    public synchronized void run() { 
     // TODO Auto-generated method stub 
     super.run(); 
     // Get a BluetoothSocket to connect with the given BluetoothDevice 

     try { 

      BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); 
      if (adapter != null) { 
       adapter.cancelDiscovery(); 
       Log.i("***Bluetooth Adapter**", "Bluetooth Discovery Canceled"); 
      } 

      if (mmSocket != null) { 

       mmSocket.connect(); 
       Log.i("***Socket Connection Successful**", "Socket Connection Successful"); 
       isDeviceConnected = true; 

       mReadData = new DataInputStream(mmSocket.getInputStream()); 
       Log.i("***Read data**", "" + mReadData); 



       if (mReadThread == null) { 
        mReadThread=new ReadThread(mReadData,mmSocket); 
        mReadThread.start(); 
       } 


      } 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      Log.e("***Error**", "Socket Connection failed"); 
      e.printStackTrace(); 
      try { 
       mmSocket.close(); 
       isDeviceConnected = false; 
      } catch (IOException closeException) { 
       e.printStackTrace(); 

      } 

     } 

     // mHandler.obtainMessage(DisplayBtdataActivity.SUCCESS_CONNECT,mmSocket).sendToTarget(); 

    } 

    /** Will cancel an in-progress connection, and close the socket */ 
    public void cancel() { 
     try { 
      mmSocket.close(); 
     } catch (IOException e) { 
     } 
    } 





    // Read the data from device 

    private class ReadThread extends Thread { 

     /** The input. */ 
     private DataInputStream input; 

     /** 
     * Constructor for ReadThread. 
     * 
     * @param input 
     *   DataInputStream 
     */ 
     private BluetoothSocket mSocket; 

     public ReadThread(DataInputStream input, BluetoothSocket socket) { 
      this.input = input; 
      this.mSocket = socket; 
     } 

     /** 
     * Method run. 
     * 
     * @see java.lang.Runnable#run() 
     */ 
     public synchronized void run() { 
      try { 
       Log.d(TAG, "ReadThread run"); 

       byte[] buffer = new byte[1024]; // buffer store for the stream 
       int bytes; // bytes returned from read() 
       bytes = input.available(); // always return 0 
       // bytes = mReadData.readInt(); 
       Log.i("***Bytes data**", "" + bytes);// print 0 
       Log.i("***Data input stream**", "" + input); // Here input is not null 

       if (input != null) { 
        Log.i("***hello world**", "..."); 
        while (isDeviceConnected) { 
         try { 

          bytes = input.read(buffer);  // this code never executes 

          Log.i("**bytes data**", " " + bytes); 

          if (input != null) { 
           int len = input.readInt(); 
           Log.i(TAG, "Response Length: " + len); 

           if (len > 65452) {// Short.MAX_VALUE*2 
            Log.i(TAG, "Error: Accesory and app are not in sync."); 
            continue; 
           } 

           Log.d(TAG, "Response Length: " + len); 
           Log.d(TAG, "Reading start time:" + System.currentTimeMillis()); 
           byte[] buf = new byte[len]; 
           Log.d(

             TAG, "input.available() " + input.available()); 
           if (input.available() > 0) { 

            input.readFully(buf); 
            System.out.println("Output:="); 


           } 

           Log.d(TAG, "Reading end time:" + System.currentTimeMillis()); 
          } 

         } catch (Exception e) { 
          Log.e(TAG, e.getMessage()); 
          isDeviceConnected = false; 

         } 
        } 

       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
       isDeviceConnected = false; 
       Log.e(TAG, "catch block 3 " + e.toString()); 

      } 
     } 

    } 

} 
+0

您是否找到針對您的問題的解決方案? – Majkl

+0

不,我還沒有找到它 – abh22ishek

回答

1

ReadThread.Run() - 你必須檢查空if (input! = null)

之前的代碼

bytes = input.available(); // Always return 0 

進入while循環

1,您使用input

2,數據連續發送,運行線程d的可能性很高o沒有收到任何數據,因此您必須將input.available bytes =();設置爲while循環。

3,你可以嘗試修改數據處理。原則上,快速讀取臨時緩衝區中的數據,然後移至MainBuffer,然後使用它進行處理。一個例子是在C# .net Xamarin,但僅舉一例:

private const int BTLPacketSize = 1024; 
    private const int BTLdataSize = 65536; 
    private System.Object InternaldataReadLock = new System.Object(); 
    private System.Object dataReadLock = new System.Object(); 
    private byte[] InternaldataRead = new byte[BTLPacketSize];//posila 64Byte pakety (resp. 62, protoze 2 jsou status bytes) 
    private byte[] TempdataRead = new byte[BTLPacketSize]; 
    private byte[] dataRead = new byte[BTLdataSize];//Tyto pameti pouzivaji cursorc -> musim ohlidat preteceni pameti//Max. prenos rychlost je 115200 b/s. 
    private bool continueRead = true; 

    public override void Run() 
    { 
     while (continueRead) 
     { 
      try 
      { 
       int readBytes = 0; 
       lock (InternaldataReadLock) 
       {//Quick reads data into bigger InternaldataRead buffer and next move only "received bytes" readBytes into TempdataRead buffer 
        readBytes = clientSocketInStream.Read(InternaldataRead, 0, InternaldataRead.Length); 
        Array.Copy(InternaldataRead, TempdataRead, readBytes); 
       } 
       if (readBytes > 0) 
       {//If something reads move it from TempdataRead into main dataRead buffer a send it into MainThread for processing. 
        lock (dataReadLock) 
        { 
         dataRead = new byte[readBytes]; 
         for (int i = 0; i < readBytes; i++) 
         { 
          dataRead[i] = TempdataRead[i]; 
         } 
        } 
        Bundle dataBundle = new Bundle(); 
        dataBundle.PutByteArray("Data", dataRead); 
        Message message = btlManager.sourceHandler.ObtainMessage(); 
        message.What = 1; 
        message.Data = dataBundle; 
        btlManager.sourceHandler.SendMessage(message); 
       } 
      } 
      catch (System.Exception e) 
      { 
       if (e is Java.IO.IOException) 
       { 
        //..... 
       } 
      } 
     } 
    }