get Bluetooth Device Services - Android Bluetooth

Android examples for Bluetooth:Bluetooth Device

Description

get Bluetooth Device Services

Demo Code


//package com.java2s;
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;
import android.util.Log;

public class Main {
    private static final String TAG = "BluetoothUtils";
    private static final boolean D = true;
    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()) {/* w  w  w  . jav a2  s .c  om*/
                String key = entry.getKey().toUpperCase();
                String value = entry.getValue();

                if (s.startsWith("0000" + key)) {
                    found = true;
                    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) {
                    if (D)
                        Log.d(TAG,
                                device.getName() + ": " + uuid.toString());
                    result.add(uuid);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            if (D)
                Log.e(TAG, "getDeviceUuids() failed", e);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            if (D)
                Log.e(TAG, "getDeviceUuids() failed", e);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            if (D)
                Log.e(TAG, "getDeviceUuids() failed", e);
        }

        return result;
    }
}

Related Tutorials