Giter Site home page Giter Site logo

litesuits / android-lite-bluetoothle Goto Github PK

View Code? Open in Web Editor NEW
968.0 64.0 320.0 287 KB

BLE Framework. Based on Bluetooth 4.0. Based on callback. Extremely simple! Communication with BluetoothLE(BLE) device as easy as HTTP communication. Android低功耗蓝牙便捷操作框架,基于回调,完成蓝牙设备交互就像发送网络请求一样简单。

Home Page: http://litesuits.com?form=gble

License: Apache License 2.0

Java 100.00%

android-lite-bluetoothle's Introduction

LiteBle: Android Bluetooth Framework

Extremely simple! Based on callback. Communication with BluetoothLE(BLE) device as easy as HTTP communication. One Device, One connection, One LiteBluetooth Instance.

But One connection can has many callback: One LiteBluetooth Instance can add many BluetoothGattCallback.

##Usage

###1. scan device

private static int TIME_OUT_SCAN = 10000;
liteBluetooth.startLeScan(new PeriodScanCallback(TIME_OUT_SCAN) {
    @Override
    public void onScanTimeout() {
        dialogShow(TIME_OUT_SCAN + " Millis Scan Timeout! ");
    }

    @Override
    public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
        BleLog.i(TAG, "device: " + device.getName() + "  mac: " + device.getAddress()
                      + "  rssi: " + rssi + "  scanRecord: " + Arrays.toString(scanRecord));
    }
});

###2. scan and connect

private static String MAC = "00:00:00:AA:AA:AA";
liteBluetooth.scanAndConnect(MAC, false, new BleGattCallback() {

    @Override
    public void onConnectSuccess(BluetoothGatt gatt, int status) {
        // discover services !
        gatt.discoverServices();
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        BluetoothUtil.printServices(gatt);
        dialogShow(MAC + " Services Discovered SUCCESS !");
    }

    @Override
    public void onConnectFailure(BleException exception) {
        bleExceptionHandler.handleException(exception);
        dialogShow(MAC + " Services Discovered FAILURE !");
    }
});

###3. get state of litebluetooth

BleLog.i(TAG, "liteBluetooth.getConnectionState: " + liteBluetooth.getConnectionState());
BleLog.i(TAG, "liteBluetooth isInScanning: " + liteBluetooth.isInScanning());
BleLog.i(TAG, "liteBluetooth isConnected: " + liteBluetooth.isConnected());
BleLog.i(TAG, "liteBluetooth isServiceDiscoered: " + liteBluetooth.isServiceDiscoered());
if (liteBluetooth.getConnectionState() >= LiteBluetooth.STATE_CONNECTING) {
    BleLog.i(TAG, "lite bluetooth is in connecting or connected");
}
if (liteBluetooth.getConnectionState() == LiteBluetooth.STATE_SERVICES_DISCOVERED) {
    BleLog.i(TAG, "lite bluetooth is in connected, services have been found");
}

###4. add(remove) new callback to an existing connection.

/**
 * add(remove) new callback to an existing connection.
 * One Device, One {@link LiteBluetooth}.
 * But one device( {@link LiteBluetooth}) can add many callback {@link BluetoothGattCallback}
 *
 * {@link LiteBleGattCallback} is a extension of {@link BluetoothGattCallback}
 */
private void addNewCallbackToOneConnection() {
    BluetoothGattCallback liteCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {}

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,
                                          BluetoothGattCharacteristic characteristic, int status) {
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {}
    };

    if (liteBluetooth.isConnectingOrConnected()) {
        liteBluetooth.addGattCallback(liteCallback);
        liteBluetooth.removeGattCallback(liteCallback);
    }
}

###5. refresh bluetooth device cache

liteBluetooth.refreshDeviceCache();

###6. close connection

if (liteBluetooth.isConnectingOrConnected()) {
    liteBluetooth.closeBluetoothGatt();
}

###7. write data to characteritic

LiteBleConnector connector = liteBluetooth.newBleConnector();
connector.withUUIDString(UUID_SERVICE, UUID_CHAR_WRITE, null)
         .writeCharacteristic(new byte[]{1, 2, 3}, new BleCharactCallback() {
             @Override
             public void onSuccess(BluetoothGattCharacteristic characteristic) {
                 BleLog.i(TAG, "Write Success, DATA: " + Arrays.toString(characteristic.getValue()));
             }

             @Override
             public void onFailure(BleException exception) {
                 BleLog.i(TAG, "Write failure: " + exception);
                 bleExceptionHandler.handleException(exception);
             }
         });

###8. write data to descriptor

LiteBleConnector connector = liteBluetooth.newBleConnector();
connector.withUUIDString(UUID_SERVICE, UUID_CHAR_WRITE, UUID_DESCRIPTOR_WRITE)
         .writeDescriptor(new byte[]{1, 2, 3}, new BleDescriptorCallback() {
             @Override
             public void onSuccess(BluetoothGattDescriptor descriptor) {
                 BleLog.i(TAG, "Write Success, DATA: " + Arrays.toString(descriptor.getValue()));
             }

             @Override
             public void onFailure(BleException exception) {
                 BleLog.i(TAG, "Write failure: " + exception);
                 bleExceptionHandler.handleException(exception);
             }
         });

###9. read data from characteritic

LiteBleConnector connector = liteBluetooth.newBleConnector();
connector.withUUIDString(UUID_SERVICE, UUID_CHAR_READ, null)
         .readCharacteristic(new BleCharactCallback() {
             @Override
             public void onSuccess(BluetoothGattCharacteristic characteristic) {
                 BleLog.i(TAG, "Read Success, DATA: " + Arrays.toString(characteristic.getValue()));
             }

             @Override
             public void onFailure(BleException exception) {
                 BleLog.i(TAG, "Read failure: " + exception);
                 bleExceptionHandler.handleException(exception);
             }
         });

###10. enable notification of characteristic

LiteBleConnector connector = liteBluetooth.newBleConnector();
connector.withUUIDString(UUID_SERVICE, UUID_CHAR_READ, null)
         .enableCharacteristicNotification(new BleCharactCallback() {
             @Override
             public void onSuccess(BluetoothGattCharacteristic characteristic) {
                 BleLog.i(TAG, "Notification characteristic Success, DATA: " + Arrays
                         .toString(characteristic.getValue()));
             }

             @Override
             public void onFailure(BleException exception) {
                 BleLog.i(TAG, "Notification characteristic failure: " + exception);
                 bleExceptionHandler.handleException(exception);
             }
         });

###11. enable notification of descriptor

LiteBleConnector connector = liteBluetooth.newBleConnector();
connector.withUUIDString(UUID_SERVICE, UUID_CHAR_READ, UUID_DESCRIPTOR_READ)
         .enableDescriptorNotification(new BleDescriptorCallback() {
             @Override
             public void onSuccess(BluetoothGattDescriptor descriptor) {
                 BleLog.i(TAG,
                         "Notification descriptor Success, DATA: " + Arrays.toString(descriptor.getValue()));
             }

             @Override
             public void onFailure(BleException exception) {
                 BleLog.i(TAG, "Notification descriptor failure : " + exception);
                 bleExceptionHandler.handleException(exception);
             }
         });

###12. read RSSI of device

liteBluetooth.newBleConnector()
             .readRemoteRssi(new BleRssiCallback() {
                 @Override
                 public void onSuccess(int rssi) {
                     BleLog.i(TAG, "Read Success, rssi: " + rssi);
                 }

                 @Override
                 public void onFailure(BleException exception) {
                     BleLog.i(TAG, "Read failure : " + exception);
                     bleExceptionHandler.handleException(exception);
                 }
             });

##More Detail, See The Sample


Website : http://litesuits.com

Email : [email protected]

QQgroup : 42960650 , 47357508

android-lite-bluetoothle's People

Contributors

litesuits 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

android-lite-bluetoothle's Issues

CallBacks executing multiple times

For example every write operation is adding new callback instance while not removing old one.
So you will get additional callback call every operation.
First write = 1 callback call
Second write = 2 callback calls and etc.

请教几个蓝牙开发遇到的问题

1.有没有遇到过用手机进行DFU升级或者频繁操作数据之后之后,用本手机连接设备调用readChararistic()读取到的数据都是乱码的,然后改用其他手机连接该设备读取到的数据就是正常的;除非关掉再打开该手机的蓝牙读取到的数据才是正常的。
2.连接蓝牙后一段时间就断开,还挺频繁的,大概是什么原因的

关于 BLUETOOTH_PRIVILEGED权限问题

FATAL EXCEPTION: main
Process: cn.com.sate.TPMS, PID: 10562
java.lang.SecurityException: Need BLUETOOTH_PRIVILEGED permission: Neither user 10110 nor current process has android.permission.BLUETOOTH_PRIVILEGED.
at android.os.Parcel.readException(Parcel.java:1620)
at android.os.Parcel.readException(Parcel.java:1573)
at android.bluetooth.IBluetoothGatt$Stub$Proxy.registerForNotification(IBluetoothGatt.java:1148)
at android.bluetooth.BluetoothGatt.setCharacteristicNotification(BluetoothGatt.java:1170)
at com.litesuits.bluetooth.conn.LiteBleConnector.setCharacteristicNotification(LiteBleConnector.java:295)
at com.litesuits.bluetooth.conn.LiteBleConnector.enableCharacteristicNotification(LiteBleConnector.java:215)
at com.litesuits.bluetooth.conn.LiteBleConnector.enableCharacteristicNotification(LiteBleConnector.java:205)
at cn.com.sate.TPMS.TPMSInterface.enableNotificationOfCharacteristic(TPMSInterface.java:141)
at cn.com.sate.TPMS.TPMSInterface$1$2.run(TPMSInterface.java:74)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5438)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)

在使用enableCharacteristicNotification方式时,报错 系统提示缺少BLUETOOTH_PRIVILEGED
这个问题该怎么解决呢?

Demo Error

示例程序报错
W/BluetoothGatt: Unhandled exception in callback
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

写数据的时候,会成功很多次

writeCharacteristic 这个发送成功以后,public void onSuccess(final BluetoothGattCharacteristic characteristic) 这个方法会执行好多次,打印的都是我发送的数据。
发送一次打印一次,发第二次的时候,会打印两次,发几次,打印几次

您好,请教两个小问题。

一个是断开连接,liteBluetooth.closeBluetoothGatt();不知道调用的时机是?我在onDestroy中调用总会报“Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.BluetoothGatt.close()' on a null object reference”这个错误。

一个是刷新cache,不好意想问下这个作用是?我也有尝试调用过,也会报空指针的错误。

还望赐教,谢谢!!

关于蓝牙的UUID相关问题,求助。

你好,我看了你的例子,确实很不错,但是我有些不明白,例如
public String UUID_SERVICE = "6e400000-0000-0000-0000-000011112222";

public String UUID_CHAR_WRITE = "6e400001-0000-0000-0000-000011112222";
public String UUID_CHAR_READ = "6e400002-0000-0000-0000-000011112222";

public String UUID_DESCRIPTOR = "00002902-0000-1000-8000-00805f9b34fb";
public String UUID_DESCRIPTOR_WRITE = "00002902-0000-1000-8000-00805f9b34fb";
public String UUID_DESCRIPTOR_READ = "00002902-0000-1000-8000-00805f9b34fb";

这些参数是怎么获取的呢,第一次接触蓝牙相关的开发,真是有些蒙了,求大神详解。。。

小米手机写入数据 报错 101

我遇到部分小米手机写入数据的时候,写入有时候一直失败。

调试显示是 BluetoothGatt 中的executeReliableWrite() 方法中返回 false,导致写入失败。日志显示
BleException { code=101, description='Initiated Exception Occurred! '}

其他手机没有改问题。

Timeout callbacks are always called

At first, I found all scan callbacks were toasted timeout, however, some of them have already connected.
Then I found all write characteristic time callback were called.
Maybe time out callback is something wrong.
Perhaps handler went on without remove callbacks ?

Gatt Exception Occurred

你好,为什么总是会抛出这个问题呢,一旦抛出这个问题,接下来重新连接将自动多次进入回调....

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.