根据mac地址进行BLE连接

public class BleService{
    private final String TAG="BleService";

    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;

    private String mBtMac;

    String bleUuid=SampleGattAttributes.DEFAULT_UUID;

    BluetoothGattCharacteristic characteristic;

    BluetoothGattCharacteristic mNotifyCharacteristic;

    private BluetoothGatt mBluetoothGatt;


    public final static UUID UUID_HEART_RATE_MEASUREMENT =
            UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);
    public final static UUID UUID_CLIENT_CHARACTERISTIC_CONFIG =
    UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG);

    private static BleService instance = null;

    public static BleService getInstance() {
        if (instance == null) {
            synchronized (BleService.class) {
                if (instance == null) {
                    instance = new BleService();
                }
            }
        }
        return instance;
    }

    public void setBleUuid(String bleUuid) {
        this.bleUuid=bleUuid;
    }

    public BluetoothGattCharacteristic getCharacteristic() {
        return characteristic;
    }

    public void setCharacteristic(BluetoothGattCharacteristic characteristic) {
        this.characteristic = characteristic;
    }

    /**
     * Initializes a reference to the local Bluetooth adapter.
     *
     * @return Return true if the initialization is successful.
     */

 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    public boolean initialize(Context context) {
        // For API level 18 and above, get a reference to BluetoothAdapter through
        // BluetoothManager.
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                L.e("Unable to initialize BluetoothManager.");
                return false;
            }
        }

        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            L.e("Unable to obtain a BluetoothAdapter.");
            return false;
        }
        return true;
    }

 

    public boolean connect(Context context,String btMac) {
        if (mBluetoothAdapter == null || btMac == null) {
            L.e("BluetoothAdapter not initialized or unspecified address.");
            return false;
        }

        // Previously connected device.  Try to reconnect.
        if (mBtMac != null && btMac.equals(mBtMac)
                && mBluetoothGatt != null) {
            L.d("Trying to use an existing mBluetoothGatt for connection.");
            return mBluetoothGatt.connect();
        }

        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(btMac);
        // We want to directly connect to the device, so we are setting the autoConnect
        // parameter to false.
        mBluetoothGatt = device.connectGatt(context, false, mGattCallback);
        Log.d(TAG,"mac:"+btMac);
        mBtMac = btMac;

        return true;
    }

 

    /**
     * After using a given BLE device, the app must call this method to ensure resources are
     * released properly.
     */
    public void disConnect() {
        if (mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.close();
        mBluetoothGatt = null;
        setCharacteristic(null);
    }

 

    // Implements callback methods for GATT events that the app cares about.  For example,
    // connection change and services discovered.
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.d(TAG, "Connected to GATT server.");
                mBluetoothGatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                App.BUS.post(new ConnectStatusEventArgs(false));
                Log.d(TAG, "Disconnected from GATT server.");
            }
        }

 

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                if (searchGattServices(getSupportedGattServices())){
                    checkCharacteristic();
                }
            }else {
                App.BUS.post(new ConnectStatusEventArgs(false));
            }
            Log.d(TAG, "onServicesDiscovered" + status);
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic,
                                         int status) {
            Log.d(TAG, "onCharacteristicRead");
            if (status == BluetoothGatt.GATT_SUCCESS) {
                postData(characteristic);
            }
        }

        /**
         * 返回数据。
         */
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {
            postData(characteristic);
        }

        private void postData(BluetoothGattCharacteristic characteristic){
            final byte[] data = characteristic.getValue();
//            if (data != null && data.length > 0) {
//                final StringBuilder stringBuilder = new StringBuilder(data.length);
//                for(byte byteChar : data)
//                {
//                    stringBuilder.append(String.format("%02X ", byteChar));
//                }
//
//            }
            App.BUS.post(new ReceiverDataEventArgs(data));
        }


    };

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private boolean checkCharacteristic(){
        BluetoothGattCharacteristic characteristic = getCharacteristic();
        if (characteristic==null){
            App.BUS.post(new ConnectStatusEventArgs(false));
            return false;
        }
        int charaProp = characteristic.getProperties();
        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {

if (mNotifyCharacteristic != null) {
                setCharacteristicNotification(
                        mNotifyCharacteristic, false);
                mNotifyCharacteristic = null;
            }
            readCharacteristic(characteristic);
        }
        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
            mNotifyCharacteristic = characteristic;
            setCharacteristicNotification(
                    characteristic, true);
        }
        App.BUS.post(new ConnectStatusEventArgs(true));
        return true;
    }

 

    /**
     * Retrieves a list of supported GATT services on the connected device. This should be
     * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
     *
     * @return A {@code List} of supported services.
     */
    public List<BluetoothGattService> getSupportedGattServices() {
        if (mBluetoothGatt == null) {
            return null;
        }
        return mBluetoothGatt.getServices();
    }

 

     /**
     * Enables or disables notification on a give characteristic.
     *
     * @param characteristic Characteristic to act on.
     * @param enabled If true, enable notification.  False otherwise.
     */
    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

        /**
         * 打开数据FFF4
         */
        // This is specific to Heart Rate Measurement.
        if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                    UUID_CLIENT_CHARACTERISTIC_CONFIG);
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            mBluetoothGatt.writeDescriptor(descriptor);
        }
    }

 

    /**
     * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
     * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
     * callback.
     *
     * @param characteristic The characteristic to read from.
     */
    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.readCharacteristic(characteristic);
    }

 

     //写入特征值
    public boolean writeCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return false;
        }
        return mBluetoothGatt.writeCharacteristic(characteristic);
    }

    public boolean sendCmd(CMD cmd) {
        return write(cmd.cmd);
    }

 

    public boolean write(byte[] cmd){
        if (getCharacteristic()!=null){
            int charaProp = this.characteristic.getProperties();
            if ((charaProp | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
                //注意: 以下读取的值 通过 BluetoothGattCallback#onCharacteristicRead() 函数返回
                this.characteristic.setValue(cmd);
                return writeCharacteristic(this.characteristic);
            }
        }
        return false;
    }

 

 private boolean searchGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null){
            return false;
        }
        String uuid;
        for (BluetoothGattService gattService : gattServices) {
            //从当前循环所指向的服务中读取特征值列表
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();
            // Loops through available Characteristics.
            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                uuid = gattCharacteristic.getUuid().toString();
                if (bleUuid.equalsIgnoreCase(uuid)){
                    setCharacteristic(gattCharacteristic);
                    return true;
                }
            }
        }
        return false;
    }

}

 

public class SampleGattAttributes {
    public static String DEFAULT_UUID = "0000fff6-0000-1000-8000-00805f9b34fb";

    public static String HEART_RATE_MEASUREMENT = "0000FFF4-0000-1000-8000-00805f9b34fb";//"00002a37-0000-1000-8000-00805f9b34fb";
    public static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";

}

 

 

    调用的方式

    public boolean connect(Context context,String strBtMac){
        if (!mBleService.initialize(context)) {
            L.e("Unable to initialize Bluetooth");
            return false;
        }
        // Automatically connects to the device upon successful start-up
        // initialization.
        mBleService.connect(context,strBtMac);
        return true;
    }

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基本的 Android BLE 蓝牙连接示例代码,用于连接指定 MAC 地址的智能血压计设备。请注意,此代码仅作为参考,具体实现可能因设备和 Android 版本而异。 首先,确保你的应用程序已经请求了蓝牙权限。 ``` <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> ``` 然后,在您的代码中,您需要使用 BluetoothAdapter 来执行扫描操作。在扫描期间,当您发现匹配的设备时,您可以使用 BluetoothDevice 对象连接到它。 ``` private BluetoothAdapter mBluetoothAdapter; private BluetoothGatt mBluetoothGatt; private BluetoothDevice mDevice; private String mDeviceAddress = "00:11:22:33:44:55"; // 初始化蓝牙适配器 final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); // 开始扫描设备 mBluetoothAdapter.startLeScan(mLeScanCallback); // 扫描回调 private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { // 扫描到指定设备 if (device.getAddress().equals(mDeviceAddress)) { mDevice = device; // 停止扫描 mBluetoothAdapter.stopLeScan(mLeScanCallback); // 连接设备 mBluetoothGatt = mDevice.connectGatt(getApplicationContext(), false, mGattCallback); } } }; ``` 在连接到设备后,您需要使用 BluetoothGattCallback 来处理连接事件、服务发现和特征写入等操作。 ``` private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { // 连接状态改变 @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { // 连接成功,开始服务发现 gatt.discoverServices(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { // 连接断开 mBluetoothGatt.close(); mBluetoothGatt = null; } } // 服务发现完成 @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { // 在这里可以连接设备的服务和特征,然后进行读/写操作 BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString(SERVICE_UUID)); BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(CHARACTERISTIC_UUID)); gatt.setCharacteristicNotification(characteristic, true); // 写入数据到设备 byte[] data = {0x01, 0x02, 0x03}; characteristic.setValue(data); gatt.writeCharacteristic(characteristic); } } // 特征写入完成 @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { // 写入完成后,可以断开连接 gatt.disconnect(); } }; ``` 最后,如果需要,在断开连接时关闭 BluetoothGatt 对象。 ``` if (mBluetoothGatt != null) { mBluetoothGatt.close(); mBluetoothGatt = null; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值