get Bluetooth Device Services by ParcelUuid - Android android.bluetooth

Android examples for android.bluetooth:Bluetooth

Description

get Bluetooth Device Services by ParcelUuid

Demo Code

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.bluetooth.BluetoothDevice;
import android.os.ParcelUuid;

public class Main {

  private static Map<String, String> uuidsDescriptions = new HashMap<String, String>();

  public static ArrayList<String> getDeviceServices(ArrayList<ParcelUuid> uuids) {
    ArrayList<String> result = new ArrayList<String>();

    for (ParcelUuid uuid : uuids) {
      String s = uuid.toString().toUpperCase();
      boolean found = false;

      for (Map.Entry<String, String> entry : uuidsDescriptions.entrySet()) {
        String key = entry.getKey().toUpperCase();
        String value = entry.getValue();

        if (s.startsWith("0000" + key)) {
          found = true;/*  w  w  w. j  a  va  2  s. c  om*/
          result.add(value);
          break;
        }
      }

      if (!found) {
        String desc = "Unknown service UUID 0x" + s.substring(4, 8);
        result.add(desc);
      }
    }

    return result;
  }

  public static ArrayList<String> getDeviceServices(BluetoothDevice device) {
    ArrayList<ParcelUuid> uuids = getDeviceUuids(device);
    return getDeviceServices(uuids);
  }

  public static ArrayList<ParcelUuid> getDeviceUuids(BluetoothDevice device) {
    ArrayList<ParcelUuid> result = new ArrayList<ParcelUuid>();

    try {
      Method method = device.getClass().getMethod("getUuids", null);
      ParcelUuid[] phoneUuids = (ParcelUuid[]) method.invoke(device, null);
      if (phoneUuids != null) {
        for (ParcelUuid uuid : phoneUuids) {

          result.add(uuid);
        }
      }
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }

    return result;
  }

}

Related Tutorials