5

Estoy desarrollando una aplicación en Android y le implemente un lector de códigos de barra bluetooth, el problema es que no he podido conseguir leer lo que el dispositivo entrega. En mi clase puedo ver y obtener los dispositivos asociados a mi teléfono pero no consigo poder leer lo que entrega.

Dejo la clase que ocupo y si alguien puede darme una ayuda con esto se agradecería.

import android.os.Bundle;
    import android.app.Activity;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothSocket;
    import android.content.BroadcastReceiver;
    import android.content.Context;

    import java.io.BufferedReader;
    import java.io.Closeable;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.Set;
    import java.util.UUID;

    import android.content.Intent;
    import android.content.IntentFilter;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;

    public class Test extends Activity {

       private static final int REQUEST_ENABLE_BT = 1;
       private Button onBtn;
       private Button offBtn;
       private Button listBtn;
       private Button findBtn;
       private TextView text;
       private BluetoothAdapter myBluetoothAdapter;
       private Set<BluetoothDevice> pairedDevices;
       private ListView myListView;
       private ArrayAdapter<String> BTArrayAdapter;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.test);

          // take an instance of BluetoothAdapter - Bluetooth radio
          myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
          if(myBluetoothAdapter == null) {
              onBtn.setEnabled(false);
              offBtn.setEnabled(false);
              listBtn.setEnabled(false);
              findBtn.setEnabled(false);
              text.setText("Status: not supported");

              Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
                     Toast.LENGTH_LONG).show();
          } else {
              text = (TextView) findViewById(R.id.text);
              onBtn = (Button)findViewById(R.id.turnOn);
              onBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    on(v);
                }
              });

              offBtn = (Button)findViewById(R.id.turnOff);
              offBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    off(v);
                }
              });

              listBtn = (Button)findViewById(R.id.paired);
              listBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    list(v);
                }
              });

              findBtn = (Button)findViewById(R.id.search);
              findBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    find(v);
                }
              });

              myListView = (ListView)findViewById(R.id.listView1);

              // create the arrayAdapter that contains the BTDevices, and set it to the ListView
              BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
              myListView.setAdapter(BTArrayAdapter);

          }
       }

       public void on(View view){
          if (!myBluetoothAdapter.isEnabled()) {
             Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
             startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);

             Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
                     Toast.LENGTH_LONG).show();
          }
          else{
             Toast.makeText(getApplicationContext(),"Bluetooth is already on",
                     Toast.LENGTH_LONG).show();
          }
       }

       @Override
       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
           // TODO Auto-generated method stub
           if(requestCode == REQUEST_ENABLE_BT){
               if(myBluetoothAdapter.isEnabled()) {
                   text.setText("Status: Enabled");
               } else {   
                   text.setText("Status: Disabled");
               }
           }
       }

       public void list(View view){
          // get paired devices
          pairedDevices = myBluetoothAdapter.getBondedDevices();

          // put it's one to the adapter
          for(BluetoothDevice device : pairedDevices)
              BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());

          Toast.makeText(getApplicationContext(),"Show Paired Devices",
                  Toast.LENGTH_SHORT).show();

       }

       final BroadcastReceiver bReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                // When discovery finds a device
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                     // Get the BluetoothDevice object from the Intent
                     BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                     // add the name and the MAC address of the object to the arrayAdapter
                     BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                     BTArrayAdapter.notifyDataSetChanged();
                }
            }
        };

       public void find(View view) {
           if (myBluetoothAdapter.isDiscovering()) {
               // the button is pressed when it discovers, so cancel the discovery
               myBluetoothAdapter.cancelDiscovery();
           }
           else {
                BTArrayAdapter.clear();
                myBluetoothAdapter.startDiscovery();

                registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));    
            }    
       }

       public void off(View view){
          myBluetoothAdapter.disable();
          text.setText("Status: Disconnected");

          Toast.makeText(getApplicationContext(),"Bluetooth turned off",
                  Toast.LENGTH_LONG).show();
       }

       @Override
       protected void onDestroy() {
           // TODO Auto-generated method stub
           super.onDestroy();
           unregisterReceiver(bReceiver);
       }
    }
2
  • ¿Cual es exactamente la pregunta? Commented el 19 feb. 2016 a las 16:04
  • Poder obtener y guardar los datos que recibo desde el dispositivo externo @Gemasoft
    – user3557
    Commented el 19 feb. 2016 a las 16:34

1 respuesta 1

4

Al parecer ni siquiera has establecido una conexión para empezar:

Define una variable global de BluetoothSocket en Activity

private BluetoothSocket mBluetoothSocket;

Después define una variable global para el identificador:

private UUID bluetoothUUID = UUID.fromString("ejemplo");

Reemplaza "ejemplo" con un UUID generado automáticamente.

Comienza con un Thread para conectarse

private class ConnectThread extends Thread {

    public ConnectThread(BluetoothDevice device) {
        try {
            mBluetoothSocket = device.createRfcommSocketToServiceRecord(device, bluetoothUUID);
        } catch (IOException e) {
            Log.e(TAG, "Error de variables:" + e.getMessage(), e);
        }
    }

    public void run() {
        try {
            mBluetoothSocket.connect();
            while (true) {
                if (mBluetoothSocket != null) {
                    mStreamThread = new StreamThread();
                    mStreamThread.start();
                    break;
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "Conexión fallida:" + e.getMessage(), e);
        }
    }

}

Después crea un Thread para aceptar conexiones.

private class AcceptThread extends Thread {

    private BluetoothServerSocket mServerSocket;

    public AcceptThread(String name) {
        try {
            mServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(name, bluetoothUUID);
        } catch (IOException e) {
            Log.e(TAG, "Error de variables:" + e.getMessage(), e);
        }
    }

    public void run() {
        while (true) {
            try {
                mBluetoothSocket = mServerSocket.accept();
                if (mBluetoothSocket != null) {
                    mStreamThread = new Streamthread();
                    mStreamThread.start();
                    break;
                }
            } catch (IOException e) {
                Log.e(TAG, "Fallido:" + e.getMessage(), e);
            }
        }
    }

Al final creamos el Thread mencionado en las 2 anteriores

private class StreamThread extends Thread {

    private InputStream in;
    private OutputStream out;

    public StreamThread() {
        try {
            in = mBluetoothSocket.getInputStream();
            out = mBluetoothSocket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "Error de variables:" + e.getMessage(), e);
        }
    }

    public void run() {
        byte[] data = new byte[1024];
        int length;
        while (true) {
            try {
                length = in.read(data);
                String text = new String(data, 0, length);
                Log.i(TAG, "Texto:" + text);
            } catch (IOException e) {
                Log.e(TAG, "Posible conexión perdida:" + e.getMessage(), e);
                break;
            }
        }

    }

    public void write(byte[] data) throws IOException {
        out.write(data);
    }

}

Para enviar datos, como por ejemplo "texto", usa el Thread de stream.

String text = "Ejemplo";
mStreamThread.write(text.getBytes());

Al iniciar la actividad (Activity), debes iniciar el Thread de aceptar.

AcceptThread accept = new AcceptThread("Ejemplo");
accept.start();

Al momento de conectarse a un dispositivo, usa el siguiente Thread de conectar.

ConnectThread connect = new ConnectThread(device);
connect.start();

Donde dice device debes un objeto BluetoothDevice.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.