2012-05-24 26 views
11

En mi proyecto tengo que leer códigos de barras utilizando el escáner de código de barras Símbolo CS3070 a través de bluetooth. es decir; Tengo que establecer una conexión entre el dispositivo Android y el escáner de código de barras a través de bluetooth. ¿Alguien puede decirme cómo leer los valores del lector de códigos de barras y cómo configurar la comunicación? Ya leí el Bluetooth Developer Guide, y no quiero usar el lector de código de barras en el modo de emulación de teclado Bluetooth (HID) (tengo una vista de texto que se puede completar con el teclado y el lector de código de barras y no puedo controlar el enfoque)Cómo leer datos del escáner de código de barras bluetooth Símbolo CS3070 a dispositivo Android

que haría uso de un hilo como este para comunicarse con un lector

private class BarcodeReaderThread extends Thread { 
    private final BluetoothServerSocket mmServerSocket; 

    public BarcodeReaderThread(UUID UUID_BLUETOOTH) { 
     // Use a temporary object that is later assigned to mmServerSocket, 
     // because mmServerSocket is final 
     BluetoothServerSocket tmp = null; 
     try { 
      // MY_UUID is the app's UUID string, also used by the client code 
      tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("BarcodeScannerForSGST", UUID_BLUETOOTH); 
      /* 
      * The UUID is also included in the SDP entry and will be the basis for the connection 
      * agreement with the client device. That is, when the client attempts to connect with this device, 
      * it will carry a UUID that uniquely identifies the service with which it wants to connect. 
      * These UUIDs must match in order for the connection to be accepted (in the next step) 
      */ 
     } catch (IOException e) { } 
     mmServerSocket = tmp; 
    } 

    public void run() { 
     BluetoothSocket socket = null; 
     // Keep listening until exception occurs or a socket is returned 
     while (true) { 
      try { 
       socket = mmServerSocket.accept(); 
       try { 
        // If a connection was accepted 
        if (socket != null) { 
         // Do work to manage the connection (in a separate thread) 
         InputStream mmInStream = null; 

         // Get the input and output streams, using temp objects because 
         // member streams are final 
         mmInStream = socket.getInputStream(); 

         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 
         // Read from the InputStream 
         bytes = mmInStream.read(buffer); 
         if (bytes > 0) { 
          // Send the obtained bytes to the UI activity 
          String readMessage = new String(buffer, 0, bytes); 
          //doMainUIOp(BARCODE_READ, readMessage); 
          if (readMessage.length() > 0 && !etMlfb.isEnabled()) //Se sono nella parte di picking 
           new ServerWorker().execute(new Object[] {LEGGI_SPED, readMessage}); 
         } 
         socket.close(); 
        } 
       } 
       catch (Exception ex) { } 
      } catch (IOException e) { 
       break; 
      } 
     } 
    } 

    /** 
    * Will cancel the listening socket, and cause the thread to finish 
    */ 
    public void cancel() { 
     try { 
      mmServerSocket.close(); 
     } catch (IOException e) { } 
    } 
} 

Gracias

+0

Necesito la misma funcionalidad en mi aplicación, amablemente dígame si encuentra algo útil relacionado con esta tarea. –

+0

También estoy tratando de lograr esto, hágamelo saber si encuentra una solución. Gracias. –

+0

No hay soluciones por ahora ... – Android84

Respuesta

12

acabo de recibir mi dispositivo y cuando emparejado y conectado el dispositivo que envía automáticamente los datos a la actualmente centrado EditText. ¿Qué versión de Android estás usando porque lo probé en ICS y JB y funcionó de esta manera? No lo he probado en ninguna versión anterior.

Editar:

cambié mi teléfono para pan de jengibre y descubrió que no funciona de la misma manera pero tengo una solución:

Esto es importante! >> Primero debe escanear el código de barras en el manual que dice "Perfil de puerto serie (SPP)".

btAdapter = BluetoothAdapter.getDefaultAdapter(); 
if (btAdapter.isEnabled()) 
{ 
    new BluetoothConnect().execute(""); 
} 

public class BluetoothConnect extends AsyncTask<String, String, Void> 
{ 
    public static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB"; 

    @Override 
    protected Void doInBackground(String... params) 
    { 
     String address = DB.GetOption("bluetoothAddress"); 
     BluetoothDevice device = btAdapter.getRemoteDevice(address); 
     try 
     { 
      socket = device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID)); 
      btAdapter.cancelDiscovery(); 
      socket.connect(); 
      InputStream stream = socket.getInputStream(); 
      int read = 0; 
      byte[] buffer = new byte[128]; 
      do 
      { 
       try 
       { 
        read = stream.read(buffer); 
        String data = new String(buffer, 0, read); 
        publishProgress(data); 
       } 
       catch(Exception ex) 
       { 
        read = -1; 
       } 
      } 
      while (read > 0); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onProgressUpdate(String... values) 
    { 
     if (values[0].equals("\r")) 
     { 
      addToList(input.getText().toString()); 
      pickupInput.setText(""); 
     } 
     else input.setText(values[0]); 
     super.onProgressUpdate(values); 
    } 
} 

Esta es una versión incompleta de mi código de trabajo, pero debería obtener la esencia.
¡Espero que esta solución también funcione para usted!

+0

+1 ¿Sería capaz de agregar el código completo? Estoy tratando de usar el mismo lector de código de barras en el modo SPP. – Baz

+0

El código que proporcioné debería ser suficiente, solo necesita saber la dirección del dispositivo. Puede obtenerlo llamando a getBondedDevices() después de su emparejamiento. Mire aquí para más información: http://developer.android.com/guide/topics/connectivity/bluetooth.html –

+0

Bien, pero ¿cómo lo uso? Como ejemplo: deseo poder leer el código de barras escaneado en un 'TextView'. ¿Cómo hago esto? – Baz

Cuestiones relacionadas