Android蓝牙BLE基本用法

Android应用权限

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

蓝牙相关对象获取

    private BluetoothAdapter bluetoothAdapter;
    private BluetoothManager bluetoothManager;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // bluetoothAdapter
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        
        // bluetoothManager BLE需要这个类
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        }
    }

检查设备是否支持BLE

public void checkBLESupport() {
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "不支持BLE", Toast.LENGTH_LONG).show();
            Log.d("kaikai", "不支持BLE");

        } else {
            Toast.makeText(this, "支持BLE", Toast.LENGTH_LONG).show();
            Log.d("kaikai", "支持BLE");
        }
    }

开启设备的蓝牙功能

public void onEnableBlueTooth() {
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, 0);
        } else {
            Toast.makeText(this, "蓝牙已开启", Toast.LENGTH_LONG).show();
        }
    }

使设备的蓝牙可被发现

public void onDiscoverable() {
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        startActivity(discoverableIntent);
        }

开启BLE服务端

新建一个GATT服务

BluetoothGattService service = new BluetoothGattService(YOUR_SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY);

新建一个GATT特征值

BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(YOUR_CHARACTERISTIC_UUID,
// 注意,如果要使特征值可写,PROPERTY需设置PROPERTY_WRITE(服务端需要返回响应)或PROPERTY_WRITE_NO_RESPONSE(服务端无需返回响应),
BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristic.PROPERTY_WRITE,
BluetoothGattCharacteristic.PERMISSION_READ | BluetoothGattCharacteristic.PERMISSION_WRITE);

注意,BluetoothGattCharacteristic构造函数的第二个参数,如果要使特征值可被客户端进行反写,需要有BluetoothGattCharacteristic.PROPERTY_WRITE或PROPERTY_WRITE_NO_RESPONSE标志位,其中,PROPERTY_WRITE标志位要求服务端在接收写请求时,返回响应,而PROPERTY_WRITE_NO_RESPONSE则不需要响应,但数据可能会被截断。

新建一个特征值描述(可选)

BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(YOUR_DESCRIPTER_UUID, BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE);

特征值加入特征值描述(可选)

characteristic.addDescriptor(descriptor);

服务加入特征值

service.addCharacteristic(characteristic);

开启GATT服务端

        // 使用一个类成员保存BluetoothGattServer引用
        private BluetoothGattServer bluetoothGattServer;


        // onCreate方法中或某个按钮触发的回调函数中
        bluetoothGattServer = bluetoothManager.openGattServer(this, new BluetoothGattServerCallback() {
                @Override
                public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
                    // 连接状态改变
                    if (newState == BluetoothProfile.STATE_CONNECTED) {
                        Log.d("kaikai", "BLE服务端:BLE Connected!");
                    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                        Log.d("kaikai", "BLE服务端:BLE Disconnected!");
                    }
                }

                @Override
                public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {

                    Log.d("kaikai", "BLE服务端:接收到特征值读请求!" + " requestId=" + requestId + " offset=" + offset);

                    BluetoothGattCharacteristic gattCharacteristic = bluetoothGattServer.getService(TIME_SERVICE_UUID).getCharacteristic(TIME_CHARACTERISTIC_UUID);
                    if (characteristic == gattCharacteristic) {
                        // 证明characteristic与通过gattServer得到的是同一个对象
                        Log.d("kaikai", "BLE服务端:same characteristic!");
                    }

                    byte[] value = characteristic.getValue();
                    if (value == null) {
                        value = "init responseData".getBytes();
                        characteri
Android中,创建Bluetooth Low Energy(BLE)服务的蓝牙socket连接可以通过以下步骤完成: 1. 配置蓝牙适配器:首先,需要获取设备的蓝牙适配器,并确保其已启用。可以使用BluetoothAdapter类的getDefaultAdapter()方法获取默认的蓝牙适配器实例,并调用isEnabled()方法检查其是否已启用。 2. 扫描设备:使用BluetoothAdapter的startLeScan()方法扫描附近的BLE设备。在回调函数onLeScan()中,可以获取到扫描到的设备列表。 3. 连接设备:在扫描到目标设备后,调用BluetoothDevice的connectGatt()方法来创建GATT连接。其中,GATT(Generic Attribute Profile)是BLE连接的框架。该方法返回BluetoothGatt对象,用于管理GATT连接。 4. 发现服务:连接成功后,调用BluetoothGatt的discoverServices()方法来发现设备提供的GATT服务。在回调函数onServicesDiscovered()中,可以获取到所有服务列表。 5. 获取服务和特征:在服务发现完成后,通过BluetoothGatt的getService()方法获取指定的GATT服务。然后,使用getService()方法获取指定服务中的GATT特征。 6. 创建并连接GATT服务器:使用Gatt连接连接函数连接设备服务器。 7. 连接成功后,可以使用BluetoothGatt的readCharacteristic()和writeCharacteristic()等方法来读取和写入GATT特征的值。 需要注意的是,BLE连接是异步的,所以在连接过程中需要实现相应的回调函数来处理连接和数据传输的事件。 以上是在Android中创建BLE服务的蓝牙socket连接的基本步骤。根据具体的使用场景和需求,可能还需要进一步处理异常情况、设置通知等操作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值