Android Bluetooth connection to send and receive data (not BLE)

  Android Bluetooth knowledge directly over, we can on Baidu search.

This code through validation project, completely OK

Directly on the code.:

  private BluetoothAdapter adapter;

1.// Access to the Bluetooth adapter

  adapter = BluetoothAdapter.getDefaultAdapter();

// Turn on Bluetooth
       if (!adapter.isEnabled()) {
           // The pop-up dialog box prompts the user to select whether to turn on Bluetooth
           Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
           startActivityForResult(intent, 0);
           // Or do not prompt, forced open
           // bAdapter.enable();
       }

2 for Bluetooth MacAddress

// Search and acquisition have been paired bluetooth
nameAddress = getPairedDevice(adapter);//Add your own definition of variables

// Gets a list of names and address list
   if (nameAddress.size() > 0) {
        blueNames = nameAddress.get(0);
         blueAddress = nameAddress.get(1);
   }

// Method for obtaining here I write the name and address are stored to the collection, in order to show in the ListView and other purposes, according to their own needs, or only return address

private ArrayList<ArrayList<String>> getPairedDevice(BluetoothAdapter adapter) {
       ArrayList<ArrayList<String>> nameAndAddress = new ArrayList<ArrayList<String>>();
     // pairedDeviceNames = new ArrayList<String>();
       pairedDeviceAddress = new ArrayList<String>();
       Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
       if (pairedDevices.size() > 0) {
           // One by one analysis
           for (BluetoothDevice devices : pairedDevices) {
               // In the collection
               pairedDeviceNames.add(devices.getName() + "\n"
                       + devices.getAddress());
               pairedDeviceAddress.add(devices.getAddress());
           }
           // Save information
           nameAndAddress.add(pairedDeviceNames);
           nameAndAddress.add(pairedDeviceAddress);
       }
       return nameAndAddress;
   }

3 Address connection through the Bluetooth device

// Connecting devices
   device = adapter.getRemoteDevice(address);
   connect(device);

public synchronized void connect(BluetoothDevice device) {
 
       connectThread = new ConnectThread(device, this, adapter, handler,handlerUpdate);
       connectThread.start();
   }

The 4 connecting Bluetooth thread class

public class ConnectThread extends Thread {

// Here the variables omitted

public ConnectThread(BluetoothDevice device, BluetoothAdapter mAdapterr) {
       this.mAdapter = mAdapter;
       int sdk = Build.VERSION.SDK_INT;
       if (sdk >= 10) {
           try {
               mySocket = device
                       .createInsecureRfcommSocketToServiceRecord(MY_UUID);
           } catch (IOException e) {
               e.printStackTrace();
           }
       } else {
           try {
               mySocket = device.createRfcommSocketToServiceRecord(MY_UUID);
           } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
       }

   }

   public void run() {
       //
       mAdapter.cancelDiscovery();
       try {
            mySocket.connect();
            // Start receiving the data sent from the remote device
           connectBluetooth = new ReceiveDatas(mySocket,receiveHandler);
           connectBluetooth.start();
       //The output stream       
           mmOutStream = mySocket.getOutputStream();
       } catch (IOException e) {
           // TODO Auto-generated catch block

           try {
               mySocket.close();
            } catch (IOException ee) {
               // TODO Auto-generated catch block
               ee.printStackTrace();
           }

       }

   }

// Write data
   /* Call this from the main Activity to send data to the remote device */
   public void sendMessage(String msg) {
       byte[] buffer = new byte[16];
       try {
           if (mmOutStream == null) {
               Log.i("info", "The output stream is empty");
               return;
           }
           // Write data
             buffer = msg.getBytes();
            mmOutStream.write(buffer);
       } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       } finally {
           try {
               if (mmOutStream != null) {
                   mmOutStream.flush();
               }
           } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
       }
   }

}

5 read data

  public class ReceiveDatas extends Thread {
// Variable skip

// Construction method
     public ReceiveDatas(BluetoothSocket socket) {

       this.mmSocket = socket;
       InputStream tempIn = null;

       // Gets the input stream
       try {
           tempIn = socket.getInputStream();
       } catch (IOException e) {
           // TODO Auto-generated catch block
       }
       mmInStream = tempIn;
   }

   @Override
   public void run() {
       byte[] buffer = new byte[1024];// Buffer data stream
       int bytes;// Returns the data
       // Listening to the input stream
       while (true) {
           try {
               bytes = mmInStream.read(buffer);
              // The data processing……


               } else {
                   Log.i("info", "Abnormal");
               }
           } catch (IOException e) {
               try {
                   if (mmInStream != null) {
                       mmInStream.close();
                   }
                   Log.i("info", "Abnormal");
                   break;
               } catch (IOException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
               }
           }
           try {
               Thread.sleep(50);// Delay
                } catch (InterruptedException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
       }
}

Posted by Gilbert at November 18, 2013 - 6:00 AM