安卓(Android) 怎么获取蓝牙rfcomm套接字(Socket)

2019年10月22日21:11:21安卓(Android) 怎么获取蓝牙rfcomm套接字(Socket)已关闭评论 358 1564字阅读5分12秒

1.简介

安卓(Android) 怎么获取蓝牙rfcomm套接字(Socket)?——请看下文。

2.示例代码

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

 


import android.bluetooth.BluetoothDevice;

import android.bluetooth.BluetoothSocket;
import android.os.Build;
import java.lang.reflect.Method;
import java.util.UUID;

public class Main {
    static final UUID BLUETOOTH_SPP_PROFILE = UUID
            .fromString("00001101-0000-1000-8000-00805F9B34FB");

    static synchronized BluetoothSocket getRfcommSocket(
            BluetoothDevice device, int numberOfRetries) {
        BluetoothSocket socket = null;
        numberOfRetries = numberOfRetries % 3;
        switch (numberOfRetries) {
        case 0:
            try {
                if (Build.VERSION.SDK_INT < 10) {
                    socket = getInsecureRfcommSocketByReflection(device);
                } else {
                    socket = device
                            .createInsecureRfcommSocketToServiceRecord(BLUETOOTH_SPP_PROFILE);
                }
                break;
            } catch (Exception e) {
            }

        case 1:
            try {
                socket = device
                        .createRfcommSocketToServiceRecord(BLUETOOTH_SPP_PROFILE);
                break;
            } catch (Exception e) {
            }

        case 2:
            try {
                socket = getRfcommSocketByReflection(device);
            } catch (Exception e) {
            }
            break;
        }
        return socket;
    }

    static synchronized BluetoothSocket getRfcommSocket(
            BluetoothDevice device) {
        return getRfcommSocket(device, 0);
    }

    private static synchronized BluetoothSocket getInsecureRfcommSocketByReflection(
            BluetoothDevice device) throws Exception {
        if (device == null)
            return null;
        Method m = device.getClass().getMethod(
                "createInsecureRfcommSocket", new Class[] { int.class });

        return (BluetoothSocket) m.invoke(device, 1);
    }

    private static synchronized BluetoothSocket getRfcommSocketByReflection(
            BluetoothDevice device) throws Exception {
        if (device == null)
            return null;
        Method m = device.getClass().getMethod("createRfcommSocket",
                new Class[] { int.class });

        return (BluetoothSocket) m.invoke(device, 1);
    }
}

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