安卓(Android) 怎么获取蓝牙设备服务(BluetoothDevice)

2019年10月24日20:29:40安卓(Android) 怎么获取蓝牙设备服务(BluetoothDevice)已关闭评论 455 1832字阅读6分6秒

1.简介

安卓(Android) 怎么获取蓝牙设备服务(BluetoothDevice)?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


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()) {
                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;
    }
}

 
继续阅读
编程十万个怎么办