From 7df8649e47746e6428b48881930923fb85c290a7 Mon Sep 17 00:00:00 2001 From: Jay Date: Tue, 22 Aug 2017 22:58:45 +0800 Subject: [PATCH] fix bug --- app/src/main/java/xyz/mtfos/btdemo/MainActivity.kt | 4 ++++ app/src/main/java/xyz/mtfos/btdemo/PrinterBle.java | 13 ++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/xyz/mtfos/btdemo/MainActivity.kt b/app/src/main/java/xyz/mtfos/btdemo/MainActivity.kt index 3461ddf..1ae0539 100644 --- a/app/src/main/java/xyz/mtfos/btdemo/MainActivity.kt +++ b/app/src/main/java/xyz/mtfos/btdemo/MainActivity.kt @@ -53,6 +53,10 @@ class MainActivity : Activity() { } } + ble?.setOnNotifyListener{ + System.out.println("Get Notify :::::: " + it) + } + var permissionCheck: Int = 0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { permissionCheck += this@MainActivity.checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) diff --git a/app/src/main/java/xyz/mtfos/btdemo/PrinterBle.java b/app/src/main/java/xyz/mtfos/btdemo/PrinterBle.java index 76e3a0a..79e1a4b 100644 --- a/app/src/main/java/xyz/mtfos/btdemo/PrinterBle.java +++ b/app/src/main/java/xyz/mtfos/btdemo/PrinterBle.java @@ -6,6 +6,7 @@ import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothManager; import android.bluetooth.le.BluetoothLeScanner; @@ -58,6 +59,7 @@ public class PrinterBle { // 藍芽狀態 public int mState = 0x00; + private boolean isConnected = false; // 藍芽通訊flag private boolean sending = false; @@ -98,6 +100,10 @@ public class PrinterBle { if(mState != DISCONNECTED) { mState = CONNECTED; Log.d(TAG, "Connected"); + if(!isConnected) { + isConnected = true; + mBtGatt.discoverServices(); + } } mHandler.postDelayed(new Runnable() { @Override @@ -105,9 +111,6 @@ public class PrinterBle { mStateListener.onChange(mState); } }, 100); - if(mState == CONNECTED) { - mBtGatt.discoverServices(); - } } else if (newState == BluetoothGatt.GATT_FAILURE) { mState = DISCONNECTED; Log.d(TAG, "Connect Failed"); @@ -125,6 +128,9 @@ public class PrinterBle { printerCharacteristic = btService.getCharacteristic(UUID.fromString(characteristicUUID)); // set notify enable mBtGatt.setCharacteristicNotification(printerCharacteristic, true); + BluetoothGattDescriptor descriptor = printerCharacteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")); + descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); + mBtGatt.writeDescriptor(descriptor); } } } @@ -262,6 +268,7 @@ public class PrinterBle { */ public void disconnect() { mState = DISCONNECTED; + isConnected = false; if (mBtGatt != null) mBtGatt.disconnect(); }