android.bluetooth.BluetoothGatt#discoverServices ( )源码实例Demo

下面列出了android.bluetooth.BluetoothGatt#discoverServices ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: SimpleBluetoothLeTerminal   文件: SerialSocket.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    // status directly taken from gat_api.h, e.g. 133=0x85=GATT_ERROR ~= timeout
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        Log.d(TAG,"connect status "+status+", discoverServices");
        if (!gatt.discoverServices())
            onSerialConnectError(new IOException("discoverServices failed"));
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        if (connected)
            onSerialIoError     (new IOException("gatt status " + status));
        else
            onSerialConnectError(new IOException("gatt status " + status));
    } else {
        Log.d(TAG, "unknown connect state "+newState+" "+status);
    }
    // continues asynchronously in onServicesDiscovered()
}
 
源代码2 项目: BTLETest   文件: MainActivity.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);
    if (newState == BluetoothGatt.STATE_CONNECTED) {
        writeLine("Connected!");
        // Discover services.
        if (!gatt.discoverServices()) {
            writeLine("Failed to start discovering services!");
        }
    }
    else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
        writeLine("Disconnected!");
    }
    else {
        writeLine("Connection state changed.  New state: " + newState);
    }
}
 
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

    super.onConnectionStateChange(gatt, status, newState);
    Log.d(TAG, "onConnectionStateChange, New state : " + newState + ", Status : " + status);

    if (status == BluetoothGatt.GATT_FAILURE) {
        EventBus.getDefault().post(new DeviceConnectionEvent(ESPConstants.EVENT_DEVICE_CONNECTION_FAILED));
        return;
    } else if (status == 133) {
        EventBus.getDefault().post(new DeviceConnectionEvent(ESPConstants.EVENT_DEVICE_CONNECTION_FAILED));
        return;
    } else if (status != BluetoothGatt.GATT_SUCCESS) {
        // TODO need to check this status
        return;
    }
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        Log.e(TAG, "Connected to GATT server.");
        gatt.discoverServices();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        Log.e(TAG, "Disconnected from GATT server.");
        EventBus.getDefault().post(new DeviceConnectionEvent(ESPConstants.EVENT_DEVICE_CONNECTION_FAILED));
    }
}
 
源代码4 项目: BLEChat   文件: BleManager.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        mState = STATE_CONNECTED;
        Logs.d(TAG, "# Connected to GATT server.");
        mHandler.obtainMessage(MESSAGE_STATE_CHANGE, STATE_CONNECTED, 0).sendToTarget();
        
        gatt.discoverServices();
        
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        mState = STATE_IDLE;
        Logs.d(TAG, "# Disconnected from GATT server.");
        mHandler.obtainMessage(MESSAGE_STATE_CHANGE, STATE_IDLE, 0).sendToTarget();
        mBluetoothGatt = null;
		mGattServices.clear();
        mDefaultService = null;
		mGattCharacteristics.clear();
		mWritableCharacteristics.clear();
        mDefaultChar = null;
        mDefaultDevice = null;
    }
}
 
源代码5 项目: BLE   文件: DeviceMirror.java
/**
 * 连接状态改变,主要用来分析设备的连接与断开
 * @param gatt GATT
 * @param status 改变前状态
 * @param newState 改变后状态
 */
@Override
public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
    ViseLog.i("onConnectionStateChange  status: " + status + " ,newState: " + newState +
            "  ,thread: " + Thread.currentThread());
    if (newState == BluetoothGatt.STATE_CONNECTED) {
        gatt.discoverServices();
    } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
        close();
        if (connectCallback != null) {
            if (handler != null) {
                handler.removeCallbacksAndMessages(null);
            }
            ViseBle.getInstance().getDeviceMirrorPool().removeDeviceMirror(deviceMirror);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                connectState = ConnectState.CONNECT_DISCONNECT;
                connectCallback.onDisconnect(isActiveDisconnect);
            } else {
                connectState = ConnectState.CONNECT_FAILURE;
                connectCallback.onConnectFailure(new ConnectException(gatt, status));
            }
        }
    } else if (newState == BluetoothGatt.STATE_CONNECTING) {
        connectState = ConnectState.CONNECT_PROCESS;
    }
}
 
源代码6 项目: android   文件: BikeService.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);

    print(String.format("status:%d, newState:%d", status, newState));

    if (status != BluetoothGatt.GATT_SUCCESS) {
        closeConnect();
    }

    switch (newState) {
        case BluetoothProfile.STATE_CONNECTED:
            print("连接GATT服务成功,开始发现服务...");
            gatt.discoverServices();
            break;
        case BluetoothProfile.STATE_DISCONNECTED:
            print("断开GATT服务,Bye");
            closeConnect();
            break;

        default:
            break;
    }
}
 
源代码7 项目: myolib   文件: BaseMyo.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTING) {
        mConnectionState = ConnectionState.CONNECTING;
    } else if (newState == BluetoothProfile.STATE_CONNECTED) {
        mConnectionState = ConnectionState.CONNECTED;
        Logy.d(TAG, "Device connected, discovering services...");
        gatt.discoverServices();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
        mConnectionState = ConnectionState.DISCONNECTING;
        mWaitToken.drainPermits();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        mConnectionState = ConnectionState.DISCONNECTED;
    } else {
        throw new RuntimeException("Unknown connection state");
    }
    Logy.d(TAG, "status:" + status + ", newState:" + mConnectionState.name());
    for (ConnectionListener listener : mConnectionListeners)
        listener.onConnectionStateChanged(this, mConnectionState);
    super.onConnectionStateChange(gatt, status, newState);
}
 
@Override
protected void transaction(GattTransactionCallback callback) {
    super.transaction(callback);
    getConnection().setState(GattState.DISCOVERING);
    boolean success;
    BluetoothGatt localGatt = getConnection().getGatt();
    if(localGatt == null) {
        Timber.w("The gatt was null during discovery, are you sure the connection wasn't cancelled?  Please make sure to handle the transaction results.");
        success = false;
    } else {
        success = localGatt.discoverServices();
    }
    if(!success) {
        getConnection().setState(GattState.DISCOVERY_FAILURE);
        TransactionResult.Builder builder = new TransactionResult.Builder();
        builder.gattState(getConnection().getGattState())
                .resultStatus(TransactionResult.TransactionResultStatus.FAILURE);
        mainThreadHandler.post(() -> {
            callCallbackWithTransactionResultAndRelease(callback, builder.build());
            getConnection().setState(GattState.IDLE);
        });
    } else {
        synchronized (NAME) {
            try {
                NAME.wait(DEFAULT_GATT_TRANSACTION_TIMEOUT);
            } catch (InterruptedException e) {
                Timber.e(e, "[%s] Not the end of the world, we'll just let it go", getDevice());
            }
        }
    }
}
 
@Override
 public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) { 
 	if (newState ==  BluetoothGatt.STATE_DISCONNECTED)
 	{
Log.e("H7ConnectThread", "device Disconnected");
ac.connectionError();
 	}
 	else{
gatt.discoverServices();
Log.d("H7ConnectThread", "Connected and discovering services");
 	}
 }
 
源代码10 项目: flutter-plugins   文件: ESenseManager.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        gatt.discoverServices();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        gatt.close();
        mCharacteristicMap.clear();
        if(mConnectionListener != null) {
            mConnectionListener.onDisconnected(ESenseManager.this);
        }
    }

}
 
源代码11 项目: thunderboard-android   文件: GattManager.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);

    BluetoothDevice device = gatt.getDevice();

    Timber.d("device: %s, status: %d, newState: %d", (device != null), status, newState);

    if (BluetoothGatt.GATT_SUCCESS != status) {
        gatt.disconnect();
        return;
    }

    if (BluetoothProfile.STATE_DISCONNECTED == newState) {
        gatt.close();
    } else if (BluetoothProfile.STATE_CONNECTED == newState) {
        gatt.discoverServices();
        preferenceManager.addConnected(device.getAddress(), device.getName());
    }

    ThunderBoardDevice bgd = bleManager.getDeviceFromCache(device.getAddress());
    if (bgd != null) {
        bgd.setState(newState);
        bleManager.selectedDeviceMonitor.onNext(bgd);
        bleManager.selectedDeviceStatusMonitor.onNext(new StatusEvent(bgd));
    }
}
 
源代码12 项目: neatle   文件: Device.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    boolean didConnect = false;
    NeatleLogger.d("onConnectionStateChange status: " + status + " newState:" + newState);
    if (newState == BluetoothGatt.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) {
        didConnect = gatt.discoverServices();
    }

    if (!didConnect) {
        gatt.close();
        connectionFailed(status);
    } else {
        connectionSuccess();
    }
}
 
源代码13 项目: PodEmu   文件: SerialInterface_BLE.java
@Override
@TargetApi(21)
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
{
    PodEmuLog.debug("SIBLE: GATT onConnectionStateChange");
    switch (newState)
    {
        case BluetoothProfile.STATE_CONNECTED:
            setState(STATE_CONNECTED);
            gatt.discoverServices();
            synchronized (SerialInterface_BLE.this)
            {
                SerialInterface_BLE.this.notifyAll();
            }
            break;
        case BluetoothProfile.STATE_CONNECTING:
            setState(STATE_CONNECTING);
            break;
        case BluetoothProfile.STATE_DISCONNECTING:
            setState(STATE_LOST);
            break;
        case BluetoothProfile.STATE_DISCONNECTED:
            setState(STATE_NONE);
            break;
    }
    //PodEmuService.communicateSerialStatusChange();
}
 
源代码14 项目: science-journal   文件: MkrSciBleManager.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
  if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
    this.gatt = gatt;
    characteristics.clear();
    gatt.discoverServices();
  } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
    readyForAction = false;
    gatt.disconnect();
  }
}
 
源代码15 项目: bean-sdk-android   文件: TestBeanBLE.java
private void discoverServices(BluetoothGatt gatt) throws InterruptedException {
    gatt.discoverServices();
    discoverServicesLatch.await(20, TimeUnit.SECONDS);
    if (discoverServicesLatch.getCount() > 0) {
        fail("FAILURE: Couldn't discover services");
    }

    Log.i(TAG, "SUCCESS: Services discovered");
}
 
源代码16 项目: physical-web   文件: BluetoothSite.java
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
  Log.i(TAG, "MTU changed to " + mtu);
  transferRate = mtu - 5;
  gatt.discoverServices();
}
 
源代码17 项目: EasyBle   文件: BleGattImpl.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, final int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);
    if (status != BluetoothGatt.GATT_SUCCESS) {
        gatt.close();
    }
    String address = gatt.getDevice().getAddress();
    Map.Entry<BleDevice, BleConnectCallback> entry = findMapEntry(mConnectCallbackMap, address);
    if (entry == null) {
        return;
    }
    final BleConnectCallback callback = entry.getValue();
    final BleDevice device = entry.getKey();
    if (status == BluetoothGatt.GATT_SUCCESS) {
        switch (newState) {
            case BluetoothProfile.STATE_CONNECTED:
                //start discovering services, only services are found do we deem
                //connection is successful
                gatt.discoverServices();
                break;
            case BluetoothProfile.STATE_DISCONNECTED:
                device.connected = false;
                refreshDeviceCache(gatt);
                gatt.close();
                removeDevice(device);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null) {
                            callback.onDisconnected("The connection has been disconnected", status, device);
                        }
                    }
                });
                break;
        }
    } else {
        removeDevice(device);
        if (device.connecting) {
            device.connecting = false;
            mHandler.removeCallbacksAndMessages(address);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onFailure(BleCallback.FAIL_OTHER, "connect fail,  status = " + status, device);
                }
            });
        } else if (device.connected && newState == BluetoothProfile.STATE_DISCONNECTED) {
            device.connected = false;
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    String tips = "The connection with remote device(mac=" + device.getDevice().getAddress() +
                            ") has been disconnected abnormally, see more details from status code";
                    callback.onDisconnected(tips, status, device);
                }
            });
        }
    }
}
 
源代码18 项目: android_wear_for_ios   文件: BLEService.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    Log.d(TAG_LOG, "onConnectionStateChange: " + status + " -> " + newState);
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        // success, connect to gatt.
        // find service
        gatt.discoverServices();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        Log.d(TAG_LOG, "onDisconnect: ");

        if(api_level >= 21) {
            if (le_scanner != null) {
                Log.d(TAG_LOG, "status: ble reset");
                stop_le_scanner();
            }
        }
        if(bluetooth_gatt != null) {
            bluetooth_gatt.disconnect();
            bluetooth_gatt.close();
            bluetooth_gatt = null;
        }
        if(bluetooth_adapter != null) {
            bluetooth_adapter = null;
        }
        is_connect = false;
        is_subscribed_characteristics = false;
        skip_count = 0;
        is_time = false;


        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
        // BluetoothAdapter through BluetoothManager.
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetooth_adapter = bluetoothManager.getAdapter();

        // Checks if Bluetooth is supported on the device.
        if (bluetooth_adapter == null) {
            Log.d(TAG_LOG, "ble adapter is null");
            return;
        }

        is_reconnect = true;
        Log.d(TAG_LOG, "start BLE scan");
        if(api_level >= 21) {
            start_le_scanner();
        }else {
            bluetooth_adapter.startLeScan(le_scan_callback);
        }
    }
}
 
源代码19 项目: Android-BLE-Library   文件: BleManagerHandler.java
@Override
public void onCharacteristicChanged(final BluetoothGatt gatt,
									final BluetoothGattCharacteristic characteristic) {
	final byte[] data = characteristic.getValue();

	if (isServiceChangedCharacteristic(characteristic)) {
		// TODO this should be tested. Should services be invalidated?
		// Forbid enqueuing more operations.
		operationInProgress = true;
		// Clear queues, services are no longer valid.
		taskQueue.clear();
		initQueue = null;
		log(Log.INFO, "Service Changed indication received");
		log(Log.VERBOSE, "Discovering Services...");
		log(Log.DEBUG, "gatt.discoverServices()");
		gatt.discoverServices();
	} else {
		final BluetoothGattDescriptor cccd =
				characteristic.getDescriptor(BleManager.CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
		final boolean notifications = cccd == null || cccd.getValue() == null ||
				cccd.getValue().length != 2 || cccd.getValue()[0] == 0x01;

		final String dataString = ParserUtils.parse(data);
		if (notifications) {
			log(Log.INFO, "Notification received from " +
					characteristic.getUuid() + ", value: " + dataString);
			onCharacteristicNotified(gatt, characteristic);
		} else { // indications
			log(Log.INFO, "Indication received from " +
					characteristic.getUuid() + ", value: " + dataString);
			onCharacteristicIndicated(gatt, characteristic);
		}
		if (batteryLevelNotificationCallback != null && isBatteryLevelCharacteristic(characteristic)) {
			batteryLevelNotificationCallback.notifyValueChanged(gatt.getDevice(), data);
		}
		// Notify the notification registered listener, if set
		final ValueChangedCallback request = valueChangedCallbacks.get(characteristic);
		if (request != null && request.matches(data)) {
			request.notifyValueChanged(gatt.getDevice(), data);
		}
		// If there is a value change request,
		if (awaitingRequest instanceof WaitForValueChangedRequest
				// registered for this characteristic
				&& awaitingRequest.characteristic == characteristic
				// and didn't have a trigger, or the trigger was started
				// (not necessarily completed)
				&& !awaitingRequest.isTriggerPending()) {
			final WaitForValueChangedRequest valueChangedRequest = (WaitForValueChangedRequest) awaitingRequest;
			if (valueChangedRequest.matches(data)) {
				// notify that new data was received.
				valueChangedRequest.notifyValueChanged(gatt.getDevice(), data);

				// If no more data are expected
				if (!valueChangedRequest.hasMore()) {
					// notify success,
					valueChangedRequest.notifySuccess(gatt.getDevice());
					// and proceed to the next request only if the trigger has completed.
					// Otherwise, the next request will be started when the request's callback
					// will be received.
					awaitingRequest = null;
					if (valueChangedRequest.isTriggerCompleteOrNull()) {
						nextRequest(true);
					}
				}
			}
		}
		if (checkCondition()) {
			nextRequest(true);
		}
	}
}
 
源代码20 项目: microbit   文件: DfuBaseService.java
@Override
        public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
            // Check whether an error occurred
            logi("onConnectionStateChange() :: Start");
            if (status == BluetoothGatt.GATT_SUCCESS) {
                if (newState == BluetoothGatt.STATE_CONNECTED) {
                    logi("onConnectionStateChange() :: Connected to GATT server");
                    mConnectionState = STATE_CONNECTED;

					/*
                     *  The onConnectionStateChange callback is called just after establishing connection and before sending Encryption Request BLE event in case of a paired device.
					 *  In that case and when the Service Changed CCCD is enabled we will get the indication after initializing the encryption, about 1600 milliseconds later. 
					 *  If we discover services right after connecting, the onServicesDiscovered callback will be called immediately, before receiving the indication and the following 
					 *  service discovery and we may end up with old, application's services instead.
					 *  
					 *  This is to support the buttonless switch from application to bootloader mode where the DFU bootloader notifies the master about service change.
					 *  Tested on Nexus 4 (Android 4.4.4 and 5), Nexus 5 (Android 5), Samsung Note 2 (Android 4.4.2). The time after connection to end of service discovery is about 1.6s 
					 *  on Samsung Note 2.
					 *  
					 *  NOTE: We are doing this to avoid the hack with calling the hidden gatt.refresh() method, at least for bonded devices.
					 */
                    if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_BONDED) {
                        try {
                            synchronized (this) {
                                logd("onConnectionStateChange() :: Waiting 1600 ms for a possible Service Changed indication...");
                                wait(1600);

                                // After 1.6s the services are already discovered so the following gatt.discoverServices() finishes almost immediately.

                                // NOTE: This also works with shorted waiting time. The gatt.discoverServices() must be called after the indication is received which is
                                // about 600ms after establishing connection. Values 600 - 1600ms should be OK.
                            }
                        } catch (InterruptedException e) {
                            Log.e(TAG, e.toString());
                            // Do nothing
                        }
                    }

                    // Attempts to discover services after successful connection.
                    final boolean success = gatt.discoverServices();
                    logi("onConnectionStateChange() :: Attempting to start service discovery... " + (success ? "succeed" : "failed"));

                    if (!success) {
                        mError = ERROR_SERVICE_DISCOVERY_NOT_STARTED;
                    } else {
                        // Just return here, lock will be notified when service discovery finishes
                        return;
                    }
                } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                    logi("onConnectionStateChange() :: Disconnected from GATT server");
                    mPaused = false;
                    mConnectionState = STATE_DISCONNECTED;
                }
            } else {
                loge("Connection state change error: " + status + " newState: " + newState);
/*				if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                    mConnectionState = STATE_DISCONNECTED;
                    if (mServicePhase == PAIRING_REQUEST ){
                        mServicePhase = PAIRING_FAILED ;
                        updateProgressNotification(status);
                    }
                }*/
                mPaused = false;
                mError = ERROR_CONNECTION_STATE_MASK | status;
            }

            // Notify waiting thread
            synchronized (mLock) {
                mLock.notifyAll();
            }
        }