下面列出了android.bluetooth.BluetoothGatt#STATE_DISCONNECTED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
}
/**
* 连接状态改变,主要用来分析设备的连接与断开
* @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;
}
}
private void closeGatt() {
if (gatt != null) {
Timber.d("gatt device: %s, connected devices: %d", gatt.getDevice().getAddress(), bluetoothManager.getConnectedDevices(BluetoothProfile.GATT).size());
ThunderBoardDevice device = getDeviceFromCache(gatt.getDevice().getAddress());
if (device != null) {
device.clear();
}
if (BluetoothGatt.STATE_DISCONNECTED == bluetoothManager.getConnectionState(gatt.getDevice(), BluetoothProfile.GATT)) {
Timber.d("close");
gatt.close();
} else {
Timber.d("disconnect");
gatt.disconnect();
}
gatt = null;
}
for (int i = 0; i < devices.size(); i++) {
Timber.d("device: %s", devices.get(i).getAddress());
}
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothGatt.STATE_CONNECTED) {
if (status == BluetoothGatt.GATT_SUCCESS) {
// Connected to device, start discovering services.
if (!gatt.discoverServices()) {
// Error starting service discovery.
connectFailure();
}
} else {
// Error connecting to device.
connectFailure();
}
} else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
// Disconnected, notify callbacks of disconnection.
rx = null;
tx = null;
notifyOnDisconnected(context);
}
}
/**
* Disconnects from the device or cancels the pending connection attempt. Does nothing if device was not connected.
* @return true if device is to be disconnected. False if it was already disconnected.
*/
public boolean disconnect() {
userDisconnected = true;
initialConnection = false;
if (bluetoothGatt != null) {
connectionState = BluetoothGatt.STATE_DISCONNECTING;
callbacks.onDeviceDisconnecting(bluetoothGatt.getDevice());
final boolean wasConnected = connected;
bluetoothGatt.disconnect();
if (!wasConnected) {
// There will be no callback, the connection attempt will be stopped
connectionState = BluetoothGatt.STATE_DISCONNECTED;
callbacks.onDeviceDisconnected(bluetoothGatt.getDevice());
}
return true;
}
return false;
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothGatt.STATE_DISCONNECTED || newState == BluetoothGatt.STATE_DISCONNECTING) {
runOnUiThread(new Runnable() {
@Override
public void run() {
disconnectWithModal();
}
});
}
}
@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");
}
}
private void notifyDeviceDisconnected(@NonNull final BluetoothDevice device, final int status) {
final boolean wasConnected = connected;
connected = false;
servicesDiscovered = false;
serviceDiscoveryRequested = false;
deviceNotSupported = false;
initInProgress = false;
connectionState = BluetoothGatt.STATE_DISCONNECTED;
checkCondition();
if (!wasConnected) {
log(Log.WARN, "Connection attempt timed out");
close();
postCallback(c -> c.onDeviceDisconnected(device));
postConnectionStateChange(o -> o.onDeviceFailedToConnect(device, status));
// ConnectRequest was already notified
} else if (userDisconnected) {
log(Log.INFO, "Disconnected");
close();
postCallback(c -> c.onDeviceDisconnected(device));
postConnectionStateChange(o -> o.onDeviceDisconnected(device, status));
final Request request = this.request;
if (request != null && request.type == Request.Type.DISCONNECT) {
request.notifySuccess(device);
}
} else {
log(Log.WARN, "Connection lost");
postCallback(c -> c.onLinkLossOccurred(device));
postConnectionStateChange(o -> o.onDeviceDisconnected(device, ConnectionObserver.REASON_LINK_LOSS));
// We are not closing the connection here as the device should try to reconnect
// automatically.
// This may be only called when the shouldAutoConnect() method returned true.
}
onDeviceDisconnected();
}
private void notifyDeviceDisconnected(final BluetoothDevice device) {
connected = false;
connectionState = BluetoothGatt.STATE_DISCONNECTED;
if (userDisconnected) {
callbacks.onDeviceDisconnected(device);
close();
} else {
callbacks.onLinklossOccurred(device);
// We are not closing the connection here as the device should try to reconnect automatically.
// This may be only called when the shouldAutoConnect() method returned true.
}
if (profile != null)
profile.release();
}
private void connectionFailed(int status) {
BluetoothGattCallback current;
int oldState;
int newState;
LinkedList<BluetoothGattCallback> queueCopy;
BluetoothGatt oldGatt;
synchronized (lock) {
oldState = state;
state = BluetoothGatt.STATE_DISCONNECTED;
newState = state;
serviceDiscovered = false;
current = currentCallback;
queueCopy = new LinkedList<>(queue);
oldGatt = this.gatt;
this.gatt = null;
}
NeatleLogger.i("Connection attempt failed. Notifying all pending operations");
current.onConnectionStateChange(oldGatt, status, BluetoothGatt.STATE_DISCONNECTED);
for (BluetoothGattCallback cb : queueCopy) {
cb.onConnectionStateChange(oldGatt, status, BluetoothGatt.STATE_DISCONNECTED);
}
notifyConnectionStateChange(oldState, newState);
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (status != BluetoothGatt.GATT_SUCCESS) {
if (getOADProfile().uploadInProgress()) {
// Since an OAD update is currently in progress, only alert the OAD Profile
// of the Bean disconnecting, not the ConnectionListener(s)
getOADProfile().onBeanConnectionFailed();
} else {
connectionListener.onConnectionFailed();
}
mConnected = false;
return;
}
if (newState == BluetoothGatt.STATE_CONNECTED) {
mConnected = true;
// Bean is connected, before alerting the ConnectionListener(s), we must
// discover available services (lookup GATT table).
Log.i(TAG, "Discovering Services!");
mGatt.discoverServices();
}
if (newState == BluetoothGatt.STATE_DISCONNECTED) {
mOperationsQueue.clear();
mOperationInProgress = false;
mConnected = false;
connectionListener.onDisconnected();
for (BaseProfile profile : mProfiles) {
profile.onBeanDisconnected();
}
}
}
/**
* Disconnects from the sensor.
*/
public final void disconnect() {
final int state = bleManager.getConnectionState();
if (state == BluetoothGatt.STATE_DISCONNECTED || state == BluetoothGatt.STATE_DISCONNECTING) {
bleManager.close();
onDeviceDisconnected(bluetoothDevice);
return;
}
bleManager.disconnect().enqueue();
}
public int getNativeConnectionState()
{
//--- > RB If BT has been turned off quickly (for instance, there are many devices connected, then you go into BT settings and run a scan), then
// we obviously won't be able to get a state. We return DISCONNECTED here for obvious reasons.
if (getManager().m_config.nativeManagerLayer.isBluetoothEnabled())
{
return m_device.layerManager().getManagerLayer().getConnectionState(m_device_native, BluetoothGatt.GATT_SERVER);
}
else
{
return BluetoothGatt.STATE_DISCONNECTED;
}
}
@Override
public void onConnectionStateChange(BluetoothDevice device, final int status, int newState) {
super.onConnectionStateChange(device, status, newState);
if (status == BluetoothGatt.GATT_SUCCESS) {
if (newState == BluetoothGatt.STATE_CONNECTED) {
mBluetoothDevices.add(device);
updateConnectedDevicesStatus();
Log.v(TAG, "Connected to device: " + device.getAddress());
} else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
mBluetoothDevices.remove(device);
updateConnectedDevicesStatus();
Log.v(TAG, "Disconnected from device");
}
} else {
mBluetoothDevices.remove(device);
updateConnectedDevicesStatus();
// There are too many gatt errors (some of them not even in the documentation) so we just
// show the error to the user.
final String errorMessage = getString(R.string.status_errorWhenConnecting) + ": " + status;
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(Peripheral.this, errorMessage, Toast.LENGTH_LONG).show();
}
});
Log.e(TAG, "Error when connecting: " + status);
}
}
public int getNativeConnectionState()
{
//--- > RB If BT has been turned off quickly (for instance, there are many devices connected, then you go into BT settings and run a scan), then
// we obviously won't be able to get a state. We return DISCONNECTED here for obvious reasons.
if (getManager().m_config.nativeManagerLayer.isBluetoothEnabled())
{
return m_device.layerManager().getManagerLayer().getConnectionState(m_device_native, BluetoothGatt.GATT_SERVER);
}
else
{
return BluetoothGatt.STATE_DISCONNECTED;
}
}
/**
* if we are connecting it start to scan the device service/characteristics otherwise it
* change the node status to idle or unreachable.
* if there is an error the node status go to dead
* @param gatt connection with the device
* @param status command status
* @param newState new node status
*/
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState){
Log.d(TAG,"Node: "+Node.this.getName()+" Status: "+status+" newState: " +
""+newState+" boundState:"+mDevice.getBondState());
if(status==BluetoothGatt.GATT_SUCCESS){
if(newState==BluetoothGatt.STATE_CONNECTED){
if (!isPairing()) { //if it is pairing we do it when it finish
//wait a bit for see if we will do the secure pairing or not,
//if the device will be in pair status the scan is aborted and will be
//done when the pairing will be completed
mBleThread.postDelayed(mScanServicesTask, RETRY_COMMAND_DELAY_MS);
}//if !pairing
}else if (newState == BluetoothGatt.STATE_DISCONNECTED){
//if the auto connect is on, avoid to close and free resources
if(!mConnectionOption.enableAutoConnect()) {
if (mConnection != null) {
if(mConnectionOption.resetCache())
refreshDeviceCache(mConnection);
if (mGattServer != null) {
mGattServer.disconnect();
}
mConnection.close();
}//if
cleanConnectionData();
}
if (mUserAskToDisconnect){
//disconnect completed
Node.this.updateNodeStatus(State.Idle);
}else{
//we disconnect but the user didn't ask it
Node.this.updateNodeStatus(State.Unreachable);
}//if else
}//if-else
}else{
//https://stackoverflow.com/questions/33718807/forcefully-turning-off-ble-device-connected-to-android-app-fires-onconnectionsta
if(status==8 && // 8 = link lost
newState == BluetoothGatt.STATE_DISCONNECTED &&
mConnectionOption.enableAutoConnect()){
Node.this.updateNodeStatus(State.Unreachable);
return;
}
//close & clean the dead connection
if(mConnection!=null) {
if (mGattServer != null) {
mGattServer.disconnect();
}
mConnection.close();
}//if
cleanConnectionData();
//notify to the user
Node.this.updateNodeStatus(State.Dead);
}//if status
}
@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();
}
}
private int performGetNativeState(AtomicInteger state, CountDownLatch latch)
{
final int reportedNativeConnectionState = getNativeConnectionState();
int connectedStateThatWeWillGoWith = reportedNativeConnectionState;
if( m_nativeConnectionState != null && m_nativeConnectionState.get() != -1 )
{
if( m_nativeConnectionState.get() != reportedNativeConnectionState )
{
getLogger().e("Tracked native state " + getLogger().gattConn(m_nativeConnectionState.get()) + " doesn't match reported state " + getLogger().gattConn(reportedNativeConnectionState) + ".");
}
connectedStateThatWeWillGoWith = m_nativeConnectionState.get();
}
if( connectedStateThatWeWillGoWith != BluetoothGatt.STATE_DISCONNECTED )
{
if( gattLayer().isGattNull() )
{
//--- DRK > Can't assert here because gatt can legitmately be null even though we have a connecting/ed native state.
//--- This was observed on the moto G right after app start up...getNativeConnectionState() reported connecting/ed
//--- but we haven't called connect yet. Really rare...only seen once after 4 months.
if( m_nativeConnectionState == null )
{
getLogger().e("Gatt is null with " + getLogger().gattConn(connectedStateThatWeWillGoWith));
connectedStateThatWeWillGoWith = BluetoothGatt.STATE_DISCONNECTED;
getManager().uhOh(UhOh.CONNECTED_WITHOUT_EVER_CONNECTING);
}
else
{
getManager().ASSERT(false, "Gatt is null with tracked native state: " + getLogger().gattConn(connectedStateThatWeWillGoWith));
}
}
}
else
{
//--- DRK > Had this assert here but must have been a brain fart because we can be disconnected
//--- but still have gatt be not null cause we're trying to reconnect.
// if( !m_mngr.ASSERT(m_gatt == null) )
// {
// m_logger.e(m_logger.gattConn(connectedStateThatWeWillGoWith));
// }
}
if (state != null)
{
state.set(connectedStateThatWeWillGoWith);
}
if (latch != null)
{
latch.countDown();
}
return connectedStateThatWeWillGoWith;
}
/**
* Returns the connection state of given device.
* @param device the target device
* @return the connection state, as in {@link BleManager#getConnectionState()}.
*/
@SuppressWarnings("unused")
public final int getConnectionState(final BluetoothDevice device) {
final BleManager manager = bleManagers.get(device);
return manager != null ? manager.getConnectionState() : BluetoothGatt.STATE_DISCONNECTED;
}
private int performGetNativeState(AtomicInteger state, CountDownLatch latch)
{
final int reportedNativeConnectionState = getNativeConnectionState();
int connectedStateThatWeWillGoWith = reportedNativeConnectionState;
if( m_nativeConnectionState != null && m_nativeConnectionState.get() != -1 )
{
if( m_nativeConnectionState.get() != reportedNativeConnectionState )
{
getLogger().e("Tracked native state " + getLogger().gattConn(m_nativeConnectionState.get()) + " doesn't match reported state " + getLogger().gattConn(reportedNativeConnectionState) + ".");
}
connectedStateThatWeWillGoWith = m_nativeConnectionState.get();
}
if( connectedStateThatWeWillGoWith != BluetoothGatt.STATE_DISCONNECTED )
{
if( gattLayer().isGattNull() )
{
//--- DRK > Can't assert here because gatt can legitmately be null even though we have a connecting/ed native state.
//--- This was observed on the moto G right after app start up...getNativeConnectionState() reported connecting/ed
//--- but we haven't called connect yet. Really rare...only seen once after 4 months.
if( m_nativeConnectionState == null )
{
getLogger().e("Gatt is null with " + getLogger().gattConn(connectedStateThatWeWillGoWith));
connectedStateThatWeWillGoWith = BluetoothGatt.STATE_DISCONNECTED;
getManager().uhOh(UhOh.CONNECTED_WITHOUT_EVER_CONNECTING);
}
else
{
getManager().ASSERT(false, "Gatt is null with tracked native state: " + getLogger().gattConn(connectedStateThatWeWillGoWith));
}
}
}
else
{
//--- DRK > Had this assert here but must have been a brain fart because we can be disconnected
//--- but still have gatt be not null cause we're trying to reconnect.
// if( !m_mngr.ASSERT(m_gatt == null) )
// {
// m_logger.e(m_logger.gattConn(connectedStateThatWeWillGoWith));
// }
}
if (state != null)
{
state.set(connectedStateThatWeWillGoWith);
}
if (latch != null)
{
latch.countDown();
}
return connectedStateThatWeWillGoWith;
}