Android How to - Get Bluetooth device names








Question

We would like to know how to get Bluetooth device names.

Answer

/*from   ww  w  .j  a v a  2  s . c  o m*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

class BluetoothUtils {
  private static final String UUID_CODE = "00001101-0000-1000-8000-00805F9B34FB";
  private ArrayList<BluetoothDevice> devices;
  private BluetoothAdapter adapter;
  
  private BluetoothSocket socket;
  
  public BluetoothUtils() {
    devices = new ArrayList<BluetoothDevice>();
    adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter == null)
      return;
    for (BluetoothDevice d : adapter.getBondedDevices())
      devices.add(d);
    
  }
  public String[] getNames() {
    String names[] = new String[devices.size()];
    for (int i = 0; i < devices.size(); i++)
      names[i] = devices.get(i).getName();
    return names;
  }
  public boolean connect(int index) {
    if (index < 0 || index >= devices.size())
      return false;
    try {
      BluetoothDevice device = devices.get(index);
      socket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString(UUID_CODE));
      socket.connect();
      return true;
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }
  }
  public void disconnect() {
    if (isConnected()) {
      try {
        socket.close();
      } catch (IOException e) {
        
      }
    }
  }
  public boolean isConnected() {
    if (socket == null)
      return false;
    
    return socket.isConnected();
  }
  public void send(int dato) {
    if (socket == null) 
      return;
    try { 
      socket.getOutputStream().write(dato);
    } catch (IOException e) {}
  }
}