2016-04-26 13 views
5

Il nostro dispositivo invia dati tramite Bluetooth, nell'app per Android è necessario leggere questi dati.La connessione BluetoothSocket per Android restituisce zero

Sono in grado di stabilire una connessione Bluetooth, e successivamente sto chiamando una discussione per stabilire la connessione BluetoothSocket tramite BluetoothDevice. Qui, quando i byte vengono letti, restituisce 0 (zero) Anche il ciclo while è in esecuzione solo una volta.

Anche l'UUID che ho usato nel codice sottostante è tratto da un codice Snippet Bluetooth. Devo ottenere l'UUID corretto del dispositivo.

Si prega di qualcuno può aiutare? .Se mi dai la risposta utile, sarà molto apprezzato.

//Calling ConnectThread after Bluetooth is paired 
    public class ConnectThread extends Thread { 
      private final BluetoothSocket mmSocket; 
      private final BluetoothDevice mmDevice; 
      private final UUID MY_UUID = UUID 
        .fromString("00001101-0000-1000-8000-00805f9b34fb"); 

      public ConnectThread(BluetoothDevice device) { 
       BluetoothSocket tmp = null; 
       mmDevice = device; 
       try { 
        String name = device.getName(); 
        Log.e("Device Name ", name); 
        tmp = device.createRfcommSocketToServiceRecord(MY_UUID); 
       } catch (IOException e) { 
       } 
       mmSocket = tmp; 
      } 

      public void run() { 
       // mAdapter.cancelDiscovery(); 
       try { 
        mmSocket.connect(); 

        ConnectedThread mConnectedThread = new ConnectedThread(mmSocket); 
        mConnectedThread.start(); 
       } catch (IOException connectException) { 
        // try { 
        // mSocket.close(); 
        // } catch (IOException closeException) { } 
        return; 
       } 
      } 

      public void cancel() { 
       try { 
        mmSocket.close(); 
       } catch (IOException e) { 
       } 
      } 
     } 

     private class ConnectedThread extends Thread { 
      private final BluetoothSocket mmSocket; 
      private final InputStream mmInStream; 
      private final OutputStream mmOutStream; 

      public ConnectedThread(BluetoothSocket socket) { 
       mmSocket = socket; 
       InputStream tmpIn = null; 
       OutputStream tmpOut = null; 
       try { 
        tmpIn = socket.getInputStream(); 
        tmpOut = socket.getOutputStream(); 
       } catch (IOException e) { 
       } 
       mmInStream = tmpIn; 
       mmOutStream = tmpOut; 
      } 

      public void run() { 
       byte[] buffer = new byte[1024]; 
       int begin = 0; 
       int bytes = 0; 
       while (true) { 
        try { 
         // bytes += mmInStream.read(buffer, bytes, buffer.length 
         // - bytes); 
         if (mmSocket.isConnected()) { 
          Log.e("Socket is connected", "Socket is connected"); 
         } 
         int numOfBytes = mmInStream.available(); 
         Log.e("numOfBytes", String.valueOf(+numOfBytes)); 
         bytes = mmInStream.read(buffer); 

         // mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) 
         // .sendToTarget(); 



        } catch (IOException e) { 
         break; 
        } 
       } 
      } 


i am struck and unable to read the data from the Bluetooth 

risposta

1

ho bisogno per ottenere il corretto UUID del dispositivo.

Sì. È possibile utilizzare getUuids() del numero BluetoothDevice che restituisce le funzionalità supportate (UUID) del dispositivo remoto o fetchUuidsWithSdp() se si desidera utilizzare UUID nuovi.

Il ciclo while è in esecuzione solo una volta.

È perché il codice sta gettando un errore e la tua stanno gestendo questo errore e uscire dal ciclo

  while (true) { 
       try { 
        // bytes += mmInStream.read(buffer, bytes, buffer.length 
        // - bytes); 
        if (mmSocket.isConnected()) { 
         Log.e("Socket is connected", "Socket is connected"); 
        } 
        int numOfBytes = mmInStream.available(); 
        Log.e("numOfBytes", String.valueOf(+numOfBytes)); 
        bytes = mmInStream.read(buffer); 

        // mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) 
        // .sendToTarget(); 



       } catch (IOException e) { 
        // THIS BREAK INTERRUPT YOUR WHILE-LOOP SENTENCE 
        break; 
       } 
      } 

qui quando i byte vengono letti sta tornando come 0

Perché hai creato un InputStream di un socket con It non connesso a nulla (perché l'UUID che hai creato per generare il socket non esiste nel dispositivo in cui hai effettuato la connessione Bluetooth)

EDIT

altro modo per ottenere UUID è config il ricevitore broadcast per ottenere indietro le UUID:

//Register the BroadcastReceiver 
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
filter.addAction(BluetoothDevice.ACTION_UUID); 
//Set your other filters 
registerReceiver(ActionFoundReceiver, filter); // Don't forget to unregister during onDestroy 

e creare il tuo BroadcastRecievier per ottenere gli UUID:

private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){ 

    @Override 
    public void onReceive(Context context, Intent intent) { 
    String action = intent.getAction(); 

     if(BluetoothDevice.ACTION_UUID.equals(action)) { 
     BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
     Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID); 
     for (int i=0; i<uuidExtra.length; i++) { 
     Log.i("TEST-UUIDS","Device: " + device.getName() + ", " + device + ", Service: " + uuidExtra[i].toString()); 
     } 
     } 
     else if(BluetoothDevice.YOUR_OTHER_ACTION_1){ 
     //YOUR CODE FOR ACTION 1 

     } 
     else if(BluetoothDevice.YOUR_OTHER_ACTION_2){ 
     //YOUR CODE FOR ACTION 2 

     } 

    } 
    }; 

Nota: non tutti i dispositivi bluetooth mostrano i loro servizi uuid

+0

Grazie per la risposta Miguel. –

+0

Ho provato a ottenere uuids usando il codice sottostante. Ma device.getUuids(); sta restituendo null. Per vostra informazione l'oggetto BluetoothDevice non è nullo ma device.getUuids() è nullo. dispositivo BluetoothDevice; try { \t \t \t \t \t \t \t ParcelUuid [] = UUID del dispositivo.getUuids(); \t \t \t \t \t \t \t per (ParcelUuid ep: UUID) { \t \t \t \t \t \t \t \t Log.e ("record UUID:", ep.toString()); \t \t \t \t \t \t \t} \t \t \t \t \t \t} catch (Exception e) { \t \t \t \t \t \t \t Log.e ("Exceptoin e", e.toString()); \t \t \t \t \t \t} –

+1

Si sta collegando con il dispositivo usando il suo indirizzo o scoprire tramite scansione e li collega con il dispositivo? –

Problemi correlati