2011-08-01 188 views
0

我需要從我的android手機發送數據到我的電腦通過藍牙功能的android模擬器。我知道需要使用客戶端和服務器端功能。但是,我不明白如何通過這些代碼調用我的方法到onCreate函數中:通過藍牙發送數據

public BluetoothSocketActivity(BluetoothDevice device) { 
     // Use a temporary object that is later assigned to mmSocket, 
     // because mmSocket is final 
     BluetoothSocket tmp = null; 
     remoteDevice = device; 

     // Get a BluetoothSocket to connect with the given BluetoothDevice 
     try { 
      // MY_UUID is the app's UUID string, also used by the server code 
      tmp = device.createRfcommSocketToServiceRecord(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666")); 
     } catch (IOException e) { } 
     mmSocket = tmp; 
    } 

    public void runConnect() { 
     // Cancel discovery because it will slow down the connection 
     _bluetooth.cancelDiscovery(); 

     try { 
      // Connect the device through the socket. This will block 
      // until it succeeds or throws an exception 
      mmSocket.connect(); 
     } catch (IOException connectException) { 
      // Unable to connect; close the socket and get out 
      try { 
       mmSocket.close(); 
      } catch (IOException closeException) { } 
      return; 
     } 

     // Do work to manage the connection (in a separate thread) 
     manageConnectedSocket(mmSocket); 

     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(BluetoothDeviceTest.MESSAGE_READ, bytes, -1, buffer) 
       .sendToTarget(); 
      } catch (IOException e) { 
       break; 
      } 
     } 
    } 

    public void write(byte[] bytes) { 
     try { 
      mmOutStream.write(bytes); 
     } catch (IOException e) { } 
    } 

    private void manageConnectedSocket(BluetoothSocket mmSocket) { 
     InputStream tmpIn = null; 
     OutputStream tmpOut = null; 

     try { 
      tmpIn = mmSocket.getInputStream(); 
      tmpOut = mmSocket.getOutputStream(); 
     } catch (IOException e) { } 

     mmInStream = tmpIn; 
     mmOutStream = tmpOut; 


    } 

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

回答

1

Android模擬器不支持藍牙。你可以看到this stackoverflow的帖子提供了一個可選庫安裝來通過TCP連接模擬藍牙。