Giter Site home page Giter Site logo

jasonchenlijian / fastble Goto Github PK

View Code? Open in Web Editor NEW
5.2K 148.0 1.2K 34.41 MB

Android Bluetooth Low Energy (BLE) Fast Development Framework. It uses simple ways to filter, scan, connect, read ,write, notify, readRssi, setMTU, and multiConnection.

License: Apache License 2.0

Java 100.00%
android bluetooth ble blue

fastble's Introduction

效果图

Thanks to the logo designed by anharismail

FastBle

Android Bluetooth Low Energy

  • Filtering, scanning, linking, reading, writing, notification subscription and cancellation in a simple way.
  • Supports acquiring signal strength and setting the maximum transmission unit.
  • Support custom scan rules
  • Support multi device connections
  • Support reconnection
  • Support configuration timeout for conncet or operation

Preview

Preview_1 Preview_2 Preview_3 Preview_4

APK

If you want to quickly preview all the functions, you can download APK as a test tool directly.

FastBLE.apk

Gradle

  • Setp1: Add it in your root build.gradle at the end of repositories

      allprojects {
          repositories {
              ...
              maven { url 'https://jitpack.io' }
          }
      }
    
  • Step2: Add the dependency

      dependencies {
          implementation 'com.github.Jasonchenlijian:FastBle:2.4.0'
      }
    

Jar

FastBLE-2.4.0.jar

Wiki

中文文档

Android BLE开发详解和FastBle源码解析

Usage

  • Init

      BleManager.getInstance().init(getApplication());
    
  • Determine whether the current Android system supports BLE

      boolean isSupportBle()
    
  • Open or close Bluetooth

      void enableBluetooth()
      void disableBluetooth()
    
  • Initialization configuration

      BleManager.getInstance()
              .enableLog(true)
              .setReConnectCount(1, 5000)
              .setSplitWriteNum(20)
              .setConnectOverTime(10000)
              .setOperateTimeout(5000);
    
  • Configuration scan rules

    void initScanRule(BleScanRuleConfig scanRuleConfig)

      BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
              .setServiceUuids(serviceUuids)
              .setDeviceName(true, names)
              .setDeviceMac(mac)
              .setAutoConnect(isAutoConnect)
              .setScanTimeOut(10000)
              .build();
      BleManager.getInstance().initScanRule(scanRuleConfig);
    

    Tips:

    • Before scanning the device, scan rules can be configured to filter out the equipment matching the program.
    • What is not configured is the default parameter
  • Scan

    void scan(BleScanCallback callback)

      BleManager.getInstance().scan(new BleScanCallback() {
          @Override
          public void onScanStarted(boolean success) {
    
          }
    
          @Override
          public void onScanning(BleDevice bleDevice) {
    
          }
    
          @Override
          public void onScanFinished(List<BleDevice> scanResultList) {
    
          }
      });
    

    Tips:

    • The scanning and filtering process is carried out in the worker thread, so it will not affect the UI operation of the main thread. Eventually, every callback result will return to the main thread.。
  • Connect with device

    BluetoothGatt connect(BleDevice bleDevice, BleGattCallback bleGattCallback)

      BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
          @Override
          public void onStartConnect() {
    
          }
    
          @Override
          public void onConnectFail(BleDevice bleDevice, BleException exception) {
    
          }
    
          @Override
          public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
    
          }
    
          @Override
          public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
    
          }
      });
    

    Tips:

    • On some types of phones, connectGatt must be effective on the main thread. It is very recommended that the connection process be placed in the main thread.
    • After connection failure, reconnect: the framework contains reconnection mechanism after connection failure, which can configure reconnection times and intervals. Of course, you can also call the connect method in onConnectFail callback automatically.
    • The connection is disconnected and reconnected: you can call the connect method again in the onDisConnected callback method.
    • In order to ensure the success rate of reconnection, it is recommended to reconnect after a period of interval.
    • When some models fail, they will be unable to scan devices for a short time. They can be connected directly through device objects or devices MAC without scanning.
  • Connect with Mac

    BluetoothGatt connect(String mac, BleGattCallback bleGattCallback)

      BleManager.getInstance().connect(mac, new BleGattCallback() {
          @Override
          public void onStartConnect() {
    
          }
    
          @Override
          public void onConnectFail(BleDevice bleDevice, BleException exception) {
    
          }
    
          @Override
          public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
    
          }
    
          @Override
          public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
    
          }
      });
    

    Tips:

    • This method can attempt to connect directly to the BLE device around the Mac without scanning.
    • In many usage scenarios, I suggest that APP save the Mac of the user's customary device, then use this method to connect, which will greatly improve the connection efficiency.
  • Scan and connect

    After scanning the first equipment that meets the scanning rules, it will stop scanning and connect to the device.

    void scanAndConnect(BleScanAndConnectCallback callback)

      BleManager.getInstance().scanAndConnect(new BleScanAndConnectCallback() {
          @Override
          public void onScanStarted(boolean success) {
    
          }
    
          @Override
          public void onScanFinished(BleDevice scanResult) {
    
          }
    
          @Override
          public void onStartConnect() {
    
          }
    
          @Override
          public void onConnectFail(BleDevice bleDevice,BleException exception) {
    
          }
    
          @Override
          public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
    
          }
    
          @Override
          public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
    
          }
      }); 
    
  • Cancel scan

    void cancelScan()

      BleManager.getInstance().cancelScan();
    

    Tips:

    • If this method is called, if it is still in the scan state, it will end immediately, and callback the onScanFinished method.
  • Notify

    void notify(BleDevice bleDevice, String uuid_service, String uuid_notify, BleNotifyCallback callback) void notify(BleDevice bleDevice, String uuid_service, String uuid_notify, boolean useCharacteristicDescriptor, BleNotifyCallback callback)

      BleManager.getInstance().notify(
              bleDevice,
              uuid_service,
              uuid_characteristic_notify,
              new BleNotifyCallback() {
                  @Override
                  public void onNotifySuccess() {
    
                  }
    
                  @Override
                  public void onNotifyFailure(BleException exception) {
    
                  }
    
                  @Override
                  public void onCharacteristicChanged(byte[] data) {
    
                  }
              });
    
  • Stop Notify

    boolean stopNotify(BleDevice bleDevice, String uuid_service, String uuid_notify) boolean stopNotify(BleDevice bleDevice, String uuid_service, String uuid_notify, boolean useCharacteristicDescriptor)

      BleManager.getInstance().stopNotify(uuid_service, uuid_characteristic_notify);
    
  • Indicate

    void indicate(BleDevice bleDevice, String uuid_service, String uuid_indicate, BleIndicateCallback callback) void indicate(BleDevice bleDevice, String uuid_service, String uuid_indicate, boolean useCharacteristicDescriptor, BleIndicateCallback callback)

      BleManager.getInstance().indicate(
              bleDevice,
              uuid_service,
              uuid_characteristic_indicate,
              new BleIndicateCallback() {
                  @Override
                  public void onIndicateSuccess() {
    
                  }
    
                  @Override
                  public void onIndicateFailure(BleException exception) {
    
                  }
    
                  @Override
                  public void onCharacteristicChanged(byte[] data) {
    
                  }
              });
    
  • Stop Indicate

    boolean stopIndicate(BleDevice bleDevice, String uuid_service, String uuid_indicate) boolean stopIndicate(BleDevice bleDevice, String uuid_service, String uuid_indicate, boolean useCharacteristicDescriptor)

      BleManager.getInstance().stopIndicate(uuid_service, uuid_characteristic_indicate);
    
  • Write

    void write(BleDevice bleDevice, String uuid_service, String uuid_write, byte[] data, BleWriteCallback callback) void write(BleDevice bleDevice, String uuid_service, String uuid_write, byte[] data, boolean split, BleWriteCallback callback) void write(BleDevice bleDevice, String uuid_service, String uuid_write, byte[] data, boolean split, boolean sendNextWhenLastSuccess, long intervalBetweenTwoPackage, BleWriteCallback callback)

      BleManager.getInstance().write(
              bleDevice,
              uuid_service,
              uuid_characteristic_write,
              data,
              new BleWriteCallback() {
                  @Override
                  public void onWriteSuccess(int current, int total, byte[] justWrite) {
    
                  }
    
                  @Override
                  public void onWriteFailure(BleException exception) {
    
                  }
              });
    

    Tips:

    • Without expanding MTU and expanding MTU's ineffectiveness, subcontracting is required when long data with more than 20 bytes are to be sent. The parameter boolean split indicates whether to use packet delivery; the write method without the boolean split parameter is subcontracted to the data by more than 20 bytes by default.
    • On the onWriteSuccess callback method: current represents the number of packets that are currently sent, and total represents the total packet data this time, and justWrite represents the successful packet that has just been sent.
  • Read

    void read(BleDevice bleDevice, String uuid_service, String uuid_read, BleReadCallback callback)

      BleManager.getInstance().read(
              bleDevice,
              uuid_service,
              uuid_characteristic_read,
              new BleReadCallback() {
                  @Override
                  public void onReadSuccess(byte[] data) {
    
                  }
    
                  @Override
                  public void onReadFailure(BleException exception) {
    
                  }
              });
    
  • Get Rssi

    void readRssi(BleDevice bleDevice, BleRssiCallback callback)

      BleManager.getInstance().readRssi(
              bleDevice,
              new BleRssiCallback() {
    
                  @Override
                  public void onRssiFailure(BleException exception) {
    
                  }
    
                  @Override
                  public void onRssiSuccess(int rssi) {
    
                  }
              });
    

    Tips:

    • Obtaining the signal strength of the device must be carried out after the device is connected.
    • Some devices may not be able to read Rssi, do not callback onRssiSuccess (), and callback onRssiFailure () because of timeout.
  • set Mtu

    void setMtu(BleDevice bleDevice, int mtu, BleMtuChangedCallback callback)

      BleManager.getInstance().setMtu(bleDevice, mtu, new BleMtuChangedCallback() {
          @Override
          public void onSetMTUFailure(BleException exception) {
    
          }
    
          @Override
          public void onMtuChanged(int mtu) {
    
          }
      });
    

    Tips:

    • Setting up MTU requires operation after the device is connected.
    • There is no such restriction in the Android Version (API-17 to API-20). Therefore, only the equipment above API21 will expand the demand for MTU.
    • The parameter MTU of the method is set to 23, and the maximum setting is 512.
    • Not every device supports the expansion of MTU, which requires both sides of the communication, that is to say, the need for the device hardware also supports the expansion of the MTU method. After calling this method, you can see through onMtuChanged (int MTU) how much the maximum transmission unit of the device is expanded to after the final setup. If the device does not support, no matter how many settings, the final MTU will be 23.
  • requestConnectionPriority

    boolean requestConnectionPriority(BleDevice bleDevice,int connectionPriority)

    Tips:

    • Request a specific connection priority. Must be one of{@link BluetoothGatt#CONNECTION_PRIORITY_BALANCED}, {@link BluetoothGatt#CONNECTION_PRIORITY_HIGH} or {@link BluetoothGatt#CONNECTION_PRIORITY_LOW_POWER}.
  • Converte BleDevice object

    BleDevice convertBleDevice(BluetoothDevice bluetoothDevice)

    BleDevice convertBleDevice(ScanResult scanResult)

    Tips:

    • The completed BleDevice object is still unconnected, if necessary, advanced connection.
  • Get all connected devices

    List<BleDevice> getAllConnectedDevice()

      BleManager.getInstance().getAllConnectedDevice();
    
  • Get a BluetoothGatt of a connected device

    BluetoothGatt getBluetoothGatt(BleDevice bleDevice)

  • Get all Service of a connected device

    List<BluetoothGattService> getBluetoothGattServices(BleDevice bleDevice)

  • Get all the Characteristic of a Service

    List<BluetoothGattCharacteristic> getBluetoothGattCharacteristics(BluetoothGattService service)

  • Determine whether a device has been connected

    boolean isConnected(BleDevice bleDevice)

      BleManager.getInstance().isConnected(bleDevice);
    

    boolean isConnected(String mac)

      BleManager.getInstance().isConnected(mac);
    
  • Determine the current connection state of a device

    int getConnectState(BleDevice bleDevice)

      BleManager.getInstance().getConnectState(bleDevice);
    
  • Disconnect a device

    void disconnect(BleDevice bleDevice)

      BleManager.getInstance().disconnect(bleDevice);
    
  • Disconnect all devices

    void disconnectAllDevice()

      BleManager.getInstance().disconnectAllDevice();
    
  • Out of use, clean up resources

    void destroy()

      BleManager.getInstance().destroy();
    
  • HexUtil

    Data operation tool class

    String formatHexString(byte[] data, boolean addSpace)

    byte[] hexStringToBytes(String hexString)

    char[] encodeHex(byte[] data, boolean toLowerCase)

  • BleDevice

    BLE device object is the smallest unit object of scanning, connection and operation in this framework.

    String getName() Bluetooth broadcast name

    String getMac() Bluetooth MAC

    byte[] getScanRecord() Broadcast data

    int getRssi() Initial signal intensity

Contact

If you have problems and ideas to communicate with me, you can contact me in the following ways.

WeChat: chenlijian1216

Email: [email protected]

License

   Copyright 2016 chenlijian

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

	   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

fastble's People

Contributors

jasonchenlijian avatar liaolintao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastble's Issues

您好,請教一個問題

請問一下,這個api可以連接microcontroller嗎?
手機設備的uuid和microcontroller好像不一樣
"fa87c0d0-afac-11de-8a39-0800200c9a66" 手機
"00001101-0000-1000-8000-00805F9B34FB" microcontroller
使用上會有差嗎?

建议:关闭连接时先移除callback

在关闭当前连接的时候, 先移除callback, 再断开连接;因为断开连接会触发连接失败的回调.

/**

  • 关闭连接
    */
    public void closeBluetoothGatt() {
    if (bleBluetooth != null) {
    bleBluetooth.clearCallback();
    bleBluetooth.closeBluetoothGatt();
    }
    }

支持蓝牙串口通讯的设备相关问题

service UUID = 0000ffe0-0000-1000-8000-00805f9b34fb
characteristic UUID = 0000ffe1-0000-1000-8000-00805f9b34fb
这个UUID 是支持蓝牙串口通讯的 所以既需要notify 也需要write
作者是每个characteristic 有且只有一个callback 。。
目前我是在write的callback的success中重新开启notify 但感觉会有实时性的问题。

Auto Connection

Is There any Option for auto connection with ble device once lost connection

Android6.0掃描不到裝置

已經在Manifest添加以下權限

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

仍然掃描不到裝置,請問能成功運行在6.0以上的解法?

程序建议

1、ListScanCallback 这个回调是在超时后才返回,如果设置超时10s或更大则回调太晚给用户体验不好
建议直接返回blueDevice
2、onLeScan device.getName()这个蓝牙名称不一定真实,需要对scanRecord进行分析得到localname才是真实的
3、增加对ble是否支持判断
4、增加对蓝牙状态监听处理
5、增加writeWithoutResponse
6、建议不用handler 进行主线程切换,建议使用org.greenrobot:eventbus:3.0.0

以上只是个人开发建议,有不当地方,还望详解。

单例模式,引用了activity的上下文, 会引起activity内存泄露

` /**

  • 初始化
    */
    public void init(Context context) {

// mContext = context;
mContext = context.getApplicationContext();

if (bleBluetooth == null) {
  bleBluetooth = new BleBluetooth(context);
}
bleBluetooth.enableBluetoothIfDisabled((Activity) context, 1);
bleExceptionHandler = new DefaultBleExceptionHandler(context);

}`

为什么indicateDevice有时候成功,有时候失败?

已经有输出设置成功,D/BleConnector: setCharacteristicIndication----true----success: true
但是最终方法返回的是false,而监听也没有成功。
使用的是同一个特征值来设置监听,为什么会这样呢?
遇到这样子的情况,需要怎么处理?

Sending more than 20 bytes for characteristic

Is it possible to write more than 20 bytes for a characteristic with the library? Using the writeDevice method it seems like it is not. What would be the best way of achieving this?

连接成功以后马上就会主动的断开

已经显示21 15:54:12.818 25288-25300/com.sita.fastbleactivity E/1000000111000: 蓝牙获取服务成功
03-21 15:54:12.818 25288-25300/com.sita.fastbleactivity D/BluetoothDevice: mAddress: A8:1B:6A:85:A8:66
03-21 15:54:12.818 25288-25300/com.sita.fastbleactivity D/BluetoothDevice: mAddress: A8:1B:6A:85:A8:66
03-21 15:54:12.819 25288-25300/com.sita.fastbleactivity D/BluetoothDevice: mAddress: A8:1B:6A:85:A8:66
03-21 15:54:12.819 25288-25300/com.sita.fastbleactivity E/1000000111000: 蓝牙特征值获取成功
03-21 15:54:12.819 25288-25300/com.sita.fastbleactivity D/BluetoothGatt: setCharacteristicNotification() - uuid: 0000ffe1-0000-1000-8000-00805f9b34fb enable: true
03-21 15:54:12.819 25288-25300/com.sita.fastbleactivity D/BluetoothDevice: mAddress: A8:1B:6A:85:A8:66
03-21 15:54:12.822 25288-25288/com.sita.fastbleactivity D/BluetoothDevice: mAddress: A8:1B:6A:85:A8:66
03-21 15:54:12.823 25288-25288/com.sita.fastbleactivity D/BleConnector: 0000ffe1-0000-1000-8000-00805f9b34fb
characteristic.getProperties():24
characteristic.getValue(): null
characteristic write bytes: [24, 24, 13, 13, 1, 0, 0, 0, 0, 0, 0, 13, 10]
hex: 18180d0d010000000000000d0a
E/FaseBlueLog: 连接失败或连接中断:201
03-21 15:54:12.998 25288-25301/com.sita.fastbleactivity E/BleExceptionHandler: Gatt Exception Occurred!

连接速度比较慢的解决办法

将BleManager.java中的

    private void connect(BluetoothDevice device, BleGattCallback callback) {
        bleBluetooth.connect(device, true, callback);
    }

这里的第二个参数是智能连接,如果开启了智能连接,会影响连接速度,我测试过,开启智能连接速度会是不开启的十倍,项目中可以修改默认为false,或者直接丢到外部给人使用,体验效果会好点

你好,有个问题请教一下

我在write的时候,会发送失败,返回值为code = 301 , description为this characteristic not support write,请问这个返回值的意思是?

当设备Android系统处于4.3以下的时候,会直接强退

在BleBluetooth.java中,使用了这个全局回调变量coreGattCallback,一旦设备不支持BLE4.0,这里就会出问题,导致实例化的时候,程序崩溃,所以,目前我的是直接在用的那里new一个,不知道还有什么解决方案
private BleGattCallback coreGattCallback = new BleGattCallback() {

    @Override
    public void onNotFoundDevice() {
        BleLog.i("coreGattCallback:onNotFoundDevice ");

        bluetoothGatt = null;
        Iterator iterator = callbackHashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object call = entry.getValue();
            if (call instanceof BleGattCallback) {
                ((BleGattCallback) call).onNotFoundDevice();
            }
        }
    }

    @Override
    public void onConnectSuccess(BluetoothGatt gatt, int status) {
        BleLog.i("coreGattCallback:onConnectSuccess ");

        bluetoothGatt = gatt;
        Iterator iterator = callbackHashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object call = entry.getValue();
            if (call instanceof BleGattCallback) {
                ((BleGattCallback) call).onConnectSuccess(gatt, status);
            }
        }
        bluetoothGatt.discoverServices();
    }

    @Override
    public void onConnectFailure(BleException exception) {
        BleLog.i("coreGattCallback:onConnectFailure ");

        bluetoothGatt = null;
        Iterator iterator = callbackHashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object call = entry.getValue();
            if (call instanceof BleGattCallback) {
                ((BleGattCallback) call).onConnectFailure(exception);
            }
        }
    }

    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        BleLog.i("coreGattCallback:onConnectionStateChange "
                + '\n' + "status: " + status
                + '\n' + "newState: " + newState
                + '\n' + "thread: " + Thread.currentThread().getId());

        if (newState == BluetoothGatt.STATE_CONNECTED) {
            connectionState = STATE_CONNECTED;
            onConnectSuccess(gatt, status);

        } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
            connectionState = STATE_DISCONNECTED;
            onConnectFailure(new ConnectException(gatt, status));

        } else if (newState == BluetoothGatt.STATE_CONNECTING) {
            connectionState = STATE_CONNECTING;
        }

        Iterator iterator = callbackHashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object call = entry.getValue();
            if (call instanceof BluetoothGattCallback) {
                ((BluetoothGattCallback) call).onConnectionStateChange(gatt, status, newState);
            }
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        BleLog.i("coreGattCallback:onServicesDiscovered ");

        connectionState = STATE_SERVICES_DISCOVERED;
        Iterator iterator = callbackHashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object call = entry.getValue();
            if (call instanceof BluetoothGattCallback) {
                ((BluetoothGattCallback) call).onServicesDiscovered(gatt, status);
            }
        }
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        BleLog.i("coreGattCallback:onCharacteristicRead ");

        Iterator iterator = callbackHashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object call = entry.getValue();
            if (call instanceof BluetoothGattCallback) {
                ((BluetoothGattCallback) call).onCharacteristicRead(gatt, characteristic, status);
            }
        }
    }

    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        BleLog.i("coreGattCallback:onCharacteristicWrite ");

        Iterator iterator = callbackHashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object call = entry.getValue();
            if (call instanceof BluetoothGattCallback) {
                ((BluetoothGattCallback) call).onCharacteristicWrite(gatt, characteristic, status);
            }
        }
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        BleLog.i("coreGattCallback:onCharacteristicChanged ");

        Iterator iterator = callbackHashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object call = entry.getValue();
            if (call instanceof BluetoothGattCallback) {
                ((BluetoothGattCallback) call).onCharacteristicChanged(gatt, characteristic);
            }
        }
    }

    @Override
    public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
        BleLog.i("coreGattCallback:onDescriptorRead ");

        Iterator iterator = callbackHashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object call = entry.getValue();
            if (call instanceof BluetoothGattCallback) {
                ((BluetoothGattCallback) call).onDescriptorRead(gatt, descriptor, status);
            }
        }
    }

    @Override
    public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
        BleLog.i("coreGattCallback:onDescriptorWrite ");

        Iterator iterator = callbackHashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object call = entry.getValue();
            if (call instanceof BluetoothGattCallback) {
                ((BluetoothGattCallback) call).onDescriptorWrite(gatt, descriptor, status);
            }
        }
    }

    @Override
    public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
        BleLog.i("coreGattCallback:onReliableWriteCompleted ");

        Iterator iterator = callbackHashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object call = entry.getValue();
            if (call instanceof BluetoothGattCallback) {
                ((BluetoothGattCallback) call).onReliableWriteCompleted(gatt, status);
            }
        }
    }

    @Override
    public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
    	
        BleLog.i("coreGattCallback:onReadRemoteRssi ");
        Iterator iterator = callbackHashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object call = entry.getValue();
            if (call instanceof BluetoothGattCallback) {
                ((BluetoothGattCallback) call).onReadRemoteRssi(gatt, rssi, status);
            }
        }
    }
};

内存泄漏

扫描完附近的设备后返回到上一页,会发生内存泄漏

连续read的话,有一些read不了,没有进入回调onCharacteristicRead

你好,看了demo是点击的时候再读的,如果我换了直接在发现服务成功后遍历读特征的话,后面的都读不出来的,没有进入onCharacteristicRead这个回调。就是如果每次只读一个的话就都可以成功,但是如果遍历读的话就只能读成功第一个,后面的都没有进入回调。想问下这个你是怎么解决的呢,感谢。

set同步问题

你好,最近看了你的BLE代码,思路上有所收获,但对于多线程操作Set时需要相应的调整,否则可能报错java.util.ConcurrentModificationException。

不满足多蓝牙连接需求~

我所在公司做的app需要连接两个蓝牙,以后可能连接更多,看了一下您的开源项目,不支持多个蓝牙同时连接,所以建议您让这个项目支持多蓝牙同时连接功能。

在Android4.4系统上连接蓝牙后,无法获取Service

在我的项目中,使用Android4.4.4的三星手机,连上蓝牙后,无法进入回调onServicesDiscovered,导致无法与蓝牙设备进行数据通信,发现在onConnectSuccess回调里面,没有调用bluetoothGatt.discoverServices(),增加之后,测试正常

每秒接收100个数据的时候会出现问题?

您好,最近看了这个项目很有帮助,但是在我使用蓝牙硬件每秒发送100个数据的时候,手机端开始接收的时候是正常的,每10ms可以接收到1个数据,但是5秒左右之后,数据接收就会变得异常,具体表现为:先是卡在某个数据不动,1s左右之后瞬间跳变几个数据,再卡在这个数据,如此往复,不像开始的时候数据接收的那么流畅,请问是线程堵塞的原因吗?程序本身应该是有数据接收就会触发回调函数来处理数据的吧?希望得到解答,谢谢!

设备返回值

你好,请问写入数据后如何接收设备的返回值呢?

点击连接时,报空指针异常,请问应该怎么修正?

com.bdk.blesample E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
com.bdk.blesample E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at java.lang.String.valueOf(String.java:1574)
at com.clj.blesample.OperateActivity.showConnectState(OperateActivity.java:263)
at com.clj.blesample.OperateActivity.access$300(OperateActivity.java:34)
at com.clj.blesample.OperateActivity$3$1.run(OperateActivity.java:169)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5136)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)

怎么扫描某一特定的设备

请问一下: 在怎么通过 service uuid 扫描出特定的设备呢?或者说有没有其他方式扫描出某一特定ble设备.

只能搜索到BLE设备吗?

RT,我尝试搜索手机的蓝牙,但是并没有搜索到手机的蓝牙,只显示了BLE设备的。是不是普通蓝牙设备,跟BLE设备是不一样,需要特别处理?

你好,startNotify方法执行了,characteristic和service的uuid也写入了,但是通知无返回值是什么情况

04-01 10:00:47.703 26119-26119/com.bdk.blesample I/OperateActivity: startNotify
04-01 10:00:47.704 26119-26119/com.bdk.blesample W/BleConnector: characteristic.getProperties():58
04-01 10:00:47.704 26119-26119/com.bdk.blesample D/BluetoothGatt: setCharacteristicNotification() - uuid: bef8d6c9-9c21-4c9e-b632-bd58c1009f9f enable: true
04-01 10:00:47.706 26119-26119/com.bdk.blesample D/BleConnector: setCharacteristicNotification: true
success: true
characteristic.getUuid(): bef8d6c9-9c21-4c9e-b632-bd58c1009f9f

1.0.3开启蓝牙问题

无法得到蓝牙使能的结果。
上一版本是可以在onActivityResult 中获取到的。

线程会不会阻塞

如果在回调函数onLeScan中添加耗时操作,请问会不会造成阻塞?

回调处理的问题

我的设备write 和 notify的uuid是一样的,hashmap的键值一样只能添加一个回调,导致收不到数据返回的通知(notify的回调被write覆盖了)

无法停止扫描

扫描蓝牙的时候,如果没有超出设定发时间再次调用bleManager.scanDevice()的时候,它会有两个扫描器同时在扫描。

提几点意见

最近也在学习蓝牙的知识,但是看了这个觉得还是很一般。
1、接口、抽象类太多,过多的抽象反而重了,而且抽象的也不是很好。比如扫描到的设备为什么要扫描结束后才返回结果而不是扫一个出现一个?另外,为什么不是用Set来去重而要用List做下判断去重?
2、封装也不是很好,比如连接服务就没必要公布出来让使用者去做。
@Override public void onConnectSuccess(BluetoothGatt gatt, int status) { gatt.discoverServices(); }
2、没有考虑6.0权限这一块儿,存在权限安全问题。
其他的还没仔细看

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.