下面列出了android.bluetooth.BluetoothGatt#STATE_CONNECTED 实例代码,或者点击链接到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);
}
}
@Override
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
NeatleLogger.i("OperationImpl: onConnectionStateChange, state:" + status + ", newState: " + newState);
Command cur;
synchronized (OperationImpl.this) {
cur = currentCommand;
if (newState != BluetoothGatt.STATE_CONNECTED && cur == EMPTY_COMMAND &&
(lastResult == null || lastResult.wasSuccessful())) {
lastResult = CommandResult.createErrorResult(null, BluetoothGatt.GATT_FAILURE);
scheduleNext();
return;
}
}
cur.onConnectionStateChange(gatt, status, newState);
}
void onConnect() {
if (mNumDevs > 0) {
int connState = mBluetoothManager.getConnectionState(mBluetoothDevice,
BluetoothGatt.GATT);
switch (connState) {
case BluetoothGatt.STATE_CONNECTED:
mBluetoothLeService.disconnect(null);
break;
case BluetoothGatt.STATE_DISCONNECTED:
boolean ok = mBluetoothLeService.connect(mBluetoothDevice.getAddress());
if (!ok) {
setError("Connect failed");
}
break;
default:
setError("Device busy (connecting/disconnecting)");
break;
}
}
}
/**
* 连接状态改变,主要用来分析设备的连接与断开
* @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;
}
}
@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(this);
}
}
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
super.onConnectionStateChange(device, status, newState);
if (newState == BluetoothGatt.STATE_DISCONNECTED) {
log(device + " has disconnected");
if (device.equals(mEddystoneGattService.getConnectedOwner())) {
log("Owner disconnected, stopping GATT server");
mEddystoneGattService.onOwnerDisconnected();
close();
}
}
else if (newState == BluetoothGatt.STATE_CONNECTED) {
log(device + " has connected");
if (mEddystoneGattService.getConnectedOwner() != null) {
// don't allow a second client to connect at the same time
log(device + " tried to connect, but owner is active. Disconnecting.");
mGattServer.cancelConnection(device);
}
}
}
@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);
}
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
Timber.d("Connection State Change");
Timber.d("Status: " + status);
Timber.d("New State: " + newState);
if (newState == BluetoothGatt.STATE_CONNECTED) {
((BaseActivity) getActivity()).dismissModalDialog();
Intent intent = getIntent(connectType, getActivity());
if (intent != null) {
bluetoothBinding.unbind();
startActivity(intent);
}
} else if (retryAttempts < MAX_RETRY_ATTEMPTS) {
retryConnectionAttempt();
} else {
((BaseActivity) getActivity()).dismissModalDialog();
bluetoothBinding.unbind();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), "Connection Failed", Toast.LENGTH_SHORT).show();
}
});
reDiscover(true);
}
}
boolean isNativelyConnected()
{
synchronized (this)
{
return getConnectionState() == BluetoothGatt.STATE_CONNECTED;
}
}
@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();
}
}
boolean isNativelyConnected()
{
synchronized (this)
{
return getConnectionState() == BluetoothGatt.STATE_CONNECTED;
}
}
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState) throws RemoteException {
BluetoothLog.v(String.format("%s.onConnectionStateChange: status = %d, newState = %d", TAG, status, newState));
if (newState == BluetoothGatt.STATE_CONNECTED) {
mHandler.sendEmptyMessageDelayed(0, NOTIFY_CYCLE);
} else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
}
}
@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();
}
}
}
public boolean areServicesDiscovered() {
synchronized (lock) {
return serviceDiscovered && state == BluetoothGatt.STATE_CONNECTED;
}
}
boolean isNativelyConnectingOrConnected()
{
int state = getConnectionState();
return state == BluetoothGatt.STATE_CONNECTED || state == BluetoothGatt.STATE_CONNECTING;
}
protected void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (status != BluetoothGatt.GATT_SUCCESS || newState != BluetoothGatt.STATE_CONNECTED) {
onError(BluetoothGatt.GATT_FAILURE);
}
}
@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();
}
}
boolean isNativelyConnectingOrConnected()
{
int state = getConnectionState();
return state == BluetoothGatt.STATE_CONNECTED || state == BluetoothGatt.STATE_CONNECTING;
}
/**
* 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 final void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
// Notify the parent activity/service
connected = true;
connectionState = BluetoothGatt.STATE_CONNECTED;
callbacks.onDeviceConnected(gatt.getDevice());
/*
* The onConnectionStateChange event is triggered just after the Android connects to a device.
* In case of bonded devices, the encryption is reestablished AFTER this callback is called.
* Moreover, when the device has Service Changed indication enabled, and the list of services has changed (e.g. using the DFU),
* the indication is received few hundred milliseconds later, depending on the connection interval.
* When received, Android will start performing a service discovery operation on its own, internally,
* and will NOT notify the app that services has changed.
*
* If the gatt.discoverServices() method would be invoked here with no delay, if would return cached services,
* as the SC indication wouldn't be received yet.
* Therefore we have to postpone the service discovery operation until we are (almost, as there is no such callback) sure,
* that it has been handled.
* TODO: Please calculate the proper delay that will work in your solution.
* It should be greater than the time from LLCP Feature Exchange to ATT Write for Service Change indication.
* If your device does not use Service Change indication (for example does not have DFU) the delay may be 0.
*/
final boolean bonded = gatt.getDevice().getBondState() == BluetoothDevice.BOND_BONDED;
final int delay = bonded ? 1600 : 0; // around 1600 ms is required when connection interval is ~45ms.
handler.postDelayed(() -> {
// Some proximity tags (e.g. nRF PROXIMITY) initialize bonding automatically when connected.
if (gatt.getDevice().getBondState() != BluetoothDevice.BOND_BONDING) {
gatt.discoverServices();
}
}, delay);
} else {
if (newState == BluetoothProfile.STATE_DISCONNECTED) {
operationInProgress = true; // no more calls are possible
initQueue = null;
taskQueue.clear();
final boolean wasConnected = connected;
// if (connected) { // Checking connected prevents from calling onDeviceDisconnected if connection attempt failed. This check is not necessary
notifyDeviceDisconnected(gatt.getDevice()); // This sets the connected flag to false
// }
// Try to reconnect if the initial connection was lost because of a link loss or timeout, and shouldAutoConnect() returned true during connection attempt.
// This time it will set the autoConnect flag to true (gatt.connect() forces autoConnect true)
if (initialConnection) {
connect(gatt.getDevice());
}
if (wasConnected || status == BluetoothGatt.GATT_SUCCESS)
return;
}
// TODO Should the disconnect method be called or the connection is still valid? Does this ever happen?
profile.onError(ERROR_CONNECTION_STATE_CHANGE, status);
}
}