2011-05-14 15 views
12

Estoy tratando de enviar datos desde android (usando API desde su SDK) a una PC usando Bluecove en Windows, siendo este el servidor.Enviar datos desde android bluetooth a la PC con bluecove

Puedo obtener el android para conectarme al servidor, pero cuando escribo en el flujo de salida del socket, no ocurre nada en el servidor. Tengo el método onPut anulado pero nunca se llama.

Código sigue abajo, si alguien me podría ayudar a que sería muy apreciado:

Android

public class BluetoothWorker { 

private static UUID generalUuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 

private static BluetoothSocket socket; 


private static BluetoothSocket getBluetoothSocket(){ 

    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    mBluetoothAdapter.cancelDiscovery(); 
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 
    // If there are paired devices 
    if (pairedDevices.size() > 0) { 
     // Loop through paired devices 
     for (BluetoothDevice device : pairedDevices) { 
      // Add the name and address to an array adapter to show in a ListView 
      if(device.getName().equalsIgnoreCase(("MIGUEL-PC"))){ 
       try { 
        return device.createRfcommSocketToServiceRecord(generalUuid); 
       } catch (IOException e) { 
        return null; 
       } 
      } 
     } 
    } 
    return null; 
} 

public static boolean sendData(String status){ 

     socket = getBluetoothSocket(); 
     try { 
      socket.connect(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      socket = null; 
     } 

    if(socket != null){ 
     try {  

      socket.getOutputStream().write(status.getBytes()); 
      socket.getOutputStream().flush(); 
      socket.close(); 
      return true; 
     } catch (IOException e) { 
      socket = null; 
      return false; 
     } 
    }else{ 
     return false; 
    } 
} 
} 

código PC

public class AISHIntegrationBTBridge { 

static final String serverUUID = "0000110100001000800000805F9B34FB"; 

public static void main(String[] args) throws IOException { 

    LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC); 

    SessionNotifier serverConnection = (SessionNotifier) Connector.open("btgoep://localhost:" 
      + serverUUID + ";name=ObexExample"); 

    int count = 0; 
    while(count < 2) { 
     RequestHandler handler = new RequestHandler(); 
     serverConnection.acceptAndOpen(handler); 

     System.out.println("Received OBEX connection " + (++count)); 
    } 
} 

private static class RequestHandler extends ServerRequestHandler { 

    public int onPut(Operation op) { 
     try { 
      HeaderSet hs = op.getReceivedHeaders(); 
      String name = (String) hs.getHeader(HeaderSet.NAME); 
      if (name != null) { 
       System.out.println("put name:" + name); 
      } 

      InputStream is = op.openInputStream(); 

      StringBuffer buf = new StringBuffer(); 
      int data; 
      while ((data = is.read()) != -1) { 
       buf.append((char) data); 
      } 

      System.out.println("got:" + buf.toString()); 

      op.close(); 
      return ResponseCodes.OBEX_HTTP_OK; 
     } catch (IOException e) { 
      e.printStackTrace(); 
      return ResponseCodes.OBEX_HTTP_UNAVAILABLE; 
     } 
    } 
} 
} 

Respuesta

8

he hecho algo similar hace 2 años.

Para Android, mi código es ligeramente diferente a la suya:

BluetoothSocket socket = Device.createRfcommSocketToServiceRecord(device_UUID); 
socket.connect(); 
DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); 

dos.writeChar('x'); // for example 

socket.close(); 

que utilizan DataOutputStream para enviar datos al PC. Pero seguramente esto no importa, solo por su referencia.

Para PC,

LocalDevice localDevice = LocalDevice.getLocalDevice(); 

localDevice.setDiscoverable(DiscoveryAgent.GIAC); // Advertising the service 

String url = "btspp://localhost:" + device_UUID + ";name=BlueToothServer"; 
StreamConnectionNotifier server = (StreamConnectionNotifier) Connector.open(url); 

StreamConnection connection = server.acceptAndOpen(); // Wait until client connects 
//=== At this point, two devices should be connected ===// 
DataInputStream dis = connection.openDataInputStream(); 

char c; 
while (true) { 
    c = dis.readChar(); 
    if (c == 'x') 
     break; 
} 

connection.close(); 

no estoy seguro de si los códigos anteriores siguen funcionando hoy en día, ya que esto se hizo hace 2 años. La API de BlueCove puede haber cambiado mucho. Pero de todos modos, estos códigos funcionan para mí. Espero que esto te pueda ayudar.

Una nota más es que tuve que desinstalar el Bluetooth Driver de Toshiba en mi PC y reinstalar el de Microsoft para poder usar BlueCove. De lo contrario, no funcionará. (Sin embargo, la última versión de BlueCove puede haber soportado diferentes controladores, por favor corrígeme si dije algo incorrecto.)

0

¡Pruebe con "println" en lugar de "escribir" en su método Android sendData!

Cuestiones relacionadas