Java Code Examples for android.bluetooth.BluetoothProfile

The following examples show how to use android.bluetooth.BluetoothProfile. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private void startBluetooth() {
	if (isBluetoothConnected) {
		Log.e("[Bluetooth] Already started, skipping...");
		return;
	}
	
	mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	
	if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
		if (mProfileListener != null) {
			Log.w("[Bluetooth] Headset profile was already opened, let's close it");
			mBluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);
		}
		
		mProfileListener = new BluetoothProfile.ServiceListener() {
			public void onServiceConnected(int profile, BluetoothProfile proxy) {
			    if (profile == BluetoothProfile.HEADSET) {
			        Log.d("[Bluetooth] Headset connected");
			        mBluetoothHeadset = (BluetoothHeadset) proxy;
			        isBluetoothConnected = true;
			    }
			}
			public void onServiceDisconnected(int profile) {
			    if (profile == BluetoothProfile.HEADSET) {
			        mBluetoothHeadset = null;
			        isBluetoothConnected = false;
			        Log.d("[Bluetooth] Headset disconnected");
			        LinphoneManager.getInstance().routeAudioToReceiver();
			    }
			}
		};
		boolean success = mBluetoothAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.HEADSET);
		if (!success) {
			Log.e("[Bluetooth] getProfileProxy failed !");
		}
	} else {
		Log.w("[Bluetooth] Interface disabled on device");
	}
}
 
Example 2
Source Project: science-journal   Source File: MyBleService.java    License: Apache License 2.0 6 votes vote down vote up
public void disconnectDevice(String address) {
  BluetoothGatt bluetoothGatt = addressToGattClient.get(address);
  if (btAdapter == null || address == null || bluetoothGatt == null) {
    // Broadcast the disconnect so BleFlow doesn't hang waiting for it; something else
    // already disconnected us in this case.
    sendGattBroadcast(address, BleEvents.GATT_DISCONNECT, null);
    return;
  }
  BluetoothDevice device = btAdapter.getRemoteDevice(address);
  int bleState = bluetoothManager.getConnectionState(device, BluetoothProfile.GATT);
  if (bleState != BluetoothProfile.STATE_DISCONNECTED
      && bleState != BluetoothProfile.STATE_DISCONNECTING) {
    bluetoothGatt.disconnect();
  } else {
    bluetoothGatt.close();
    addressToGattClient.remove(address);
    sendGattBroadcast(address, BleEvents.GATT_DISCONNECT, null);
  }
}
 
Example 3
/**
 * Disconnects from the device and closes the Bluetooth GATT object afterwards.
 */
public void disconnectAndClose() {
    // This sometimes happen when called from UpdateService.ACTION_GATT_ERROR event receiver in UpdateFragment.
    if (mBluetoothGatt == null)
        return;

    setState(STATE_DISCONNECTING);
    mBluetoothGatt.disconnect();

    // Sometimes the connection gets error 129 or 133. Calling disconnect() method does not really disconnect... sometimes the connection is already broken.
    // Here we have a security check that notifies UI about disconnection even if onConnectionStateChange(...) has not been called.
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (mConnectionState == STATE_DISCONNECTING)
                mGattCallback.onConnectionStateChange(mBluetoothGatt, BluetoothGatt.GATT_SUCCESS, BluetoothProfile.STATE_DISCONNECTED);
        }
    }, 1500);
}
 
Example 4
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
		int newState) {
	String intentAction;
	if (newState == BluetoothProfile.STATE_CONNECTED) {
		intentAction = ACTION_GATT_CONNECTED;
		mConnectionState = STATE_CONNECTED;
		broadcastUpdate(intentAction);
		Log.i(TAG, "Connected to GATT server.");
		// Attempts to discover services after successful connection.
		Log.i(TAG, "Attempting to start service discovery:"
				+ mBluetoothGatt.discoverServices());

	} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
		intentAction = ACTION_GATT_DISCONNECTED;
		mConnectionState = STATE_DISCONNECTED;
		Log.i(TAG, "Disconnected from GATT server.");
		broadcastUpdate(intentAction);
	}
}
 
Example 5
Source Project: BLEChat   Source File: BleManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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;
    }
}
 
Example 6
Source Project: wearmouse   Source File: HidDataSender.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@MainThread
public void onConnectionStateChanged(BluetoothDevice device, int state) {
    synchronized (lock) {
        if (state == BluetoothProfile.STATE_CONNECTED) {
            // A new connection was established. If we weren't expecting that, it
            // must be an incoming one. In that case, we shouldn't try to disconnect
            // from it.
            waitingForDevice = device;
        } else if (state == BluetoothProfile.STATE_DISCONNECTED) {
            // If we are disconnected from a device we are waiting to connect to, we
            // ran into a timeout and should no longer try to connect.
            if (device == waitingForDevice) {
                waitingForDevice = null;
            }
        }
        updateDeviceList();
        for (ProfileListener listener : listeners) {
            listener.onConnectionStateChanged(device, state);
        }
    }
}
 
Example 7
Source Project: xDrip-plus   Source File: ShareTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void attemptConnection() {
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (device != null) {
        details.append("\nConnection state: " + " Device is not null");
        mConnectionState = mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT);
    }

    Log.i(TAG, "Connection state: " + mConnectionState);
    details.append("\nConnection state: " + mConnectionState);
    if (mConnectionState == STATE_DISCONNECTED || mConnectionState == STATE_DISCONNECTING) {
        ActiveBluetoothDevice btDevice = new Select().from(ActiveBluetoothDevice.class)
                .orderBy("_ID desc")
                .executeSingle();
        if (btDevice != null) {
            details.append("\nBT Device: " + btDevice.name);
            mDeviceName = btDevice.name;
            mDeviceAddress = btDevice.address;
            mBluetoothAdapter = mBluetoothManager.getAdapter();
            boolean newConnection = true;
            if(newConnection) {
                is_connected = connect(mDeviceAddress);
                details.append("\nConnecting...: ");
            }
        }
    }
}
 
Example 8
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;
        broadcastUpdate(intentAction);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_GATT_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction);
    }
}
 
Example 9
Source Project: bleYan   Source File: BleUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static String getBleConnectStatus(int status) {
    switch (status) {
        case BluetoothProfile.STATE_DISCONNECTED:
            return "STATE_DISCONNECTED";

        case BluetoothProfile.STATE_CONNECTING:
            return "STATE_CONNECTING";

        case BluetoothProfile.STATE_CONNECTED:
            return "STATE_CONNECTED";

        case BluetoothProfile.STATE_DISCONNECTING:
            return "STATE_DISCONNECTING";

        default:
            return "STATE_UNKNOWN: " + status;
    }
}
 
Example 10
/**
 * Disconnects from the device and closes the Bluetooth GATT object afterwards.
 */
public void disconnectAndClose() {
	// This sometimes happen when called from UpdateService.ACTION_GATT_ERROR event receiver in UpdateFragment.
	if (mBluetoothGatt == null)
		return;

	setState(STATE_DISCONNECTING);
	mBluetoothGatt.disconnect();

	// Sometimes the connection gets error 129 or 133. Calling disconnect() method does not really disconnect... sometimes the connection is already broken.
	// Here we have a security check that notifies UI about disconnection even if onConnectionStateChange(...) has not been called. 
	mHandler.postDelayed(new Runnable() {
		@Override
		public void run() {
			if (mConnectionState == STATE_DISCONNECTING)
				mGattCallback.onConnectionStateChange(mBluetoothGatt, BluetoothGatt.GATT_SUCCESS, BluetoothProfile.STATE_DISCONNECTED);
		}
	}, 1500);
}
 
Example 11
/**
 * Converts the connection state to String value.
 *
 * @param state the connection state
 * @return state as String
 */
@NonNull
public static String stateToString(@ConnectionState final int state) {
	switch (state) {
		case BluetoothProfile.STATE_CONNECTED:
			return "CONNECTED";
		case BluetoothProfile.STATE_CONNECTING:
			return "CONNECTING";
		case BluetoothProfile.STATE_DISCONNECTING:
			return "DISCONNECTING";
		case BluetoothProfile.STATE_DISCONNECTED:
			return "DISCONNECTED";
		default:
			return "UNKNOWN (" + state + ")";
	}
}
 
Example 12
Source Project: ESeal   Source File: ACSUtilityService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    Message msg = null;
    //msg = mEventHandler.obtainMessage(EVENT_DATA_AVAILABLE);
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        //intentAction = ACTION_GATT_CONNECTED;
        mConnectionState = STATE_CONNECTED;
        msg = mCurrentEventHandler.obtainMessage(EVENT_GATT_CONNECTED);
        //broadcastUpdate(intentAction);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        //intentAction = ACTION_GATT_DISCONNECTED;
        mConnectionState = STATE_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        close();
        msg = mCurrentEventHandler.obtainMessage(EVENT_GATT_DISCONNECTED);
        mBluetoothDeviceAddress = null;
        //broadcastUpdate(intentAction);
    }
    msg.sendToTarget();
}
 
Example 13
Source Project: blessed-android   Source File: BluetoothPeripheral.java    License: MIT License 6 votes vote down vote up
/**
 * Disconnect the bluetooth peripheral.
 *
 * <p>When the disconnection has been completed {@link BluetoothCentralCallback#onDisconnectedPeripheral(BluetoothPeripheral, int)} will be called.
 */
private void disconnect() {
    if (state == BluetoothProfile.STATE_CONNECTED || state == BluetoothProfile.STATE_CONNECTING) {
        this.state = BluetoothProfile.STATE_DISCONNECTING;
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                if (bluetoothGatt != null) {
                    Timber.i("force disconnect '%s' (%s)", getName(), getAddress());
                    bluetoothGatt.disconnect();
                }
            }
        });
    } else {
        if (listener != null) {
            listener.disconnected(BluetoothPeripheral.this, GATT_CONN_TERMINATE_LOCAL_HOST);
        }
    }
}
 
Example 14
public void stopBluetooth() {
	Log.w("[Bluetooth] Stopping...");
	isBluetoothConnected = false;
	
	disableBluetoothSCO();
	
	if (mBluetoothAdapter != null && mProfileListener != null && mBluetoothHeadset != null) {
		mBluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);
		mProfileListener = null;
	}
	mBluetoothDevice = null;
	
	Log.w("[Bluetooth] Stopped!");
	
	if (LinphoneManager.isInstanciated()) {
		LinphoneManager.getInstance().routeAudioToReceiver();
	}
}
 
Example 15
Source Project: xDrip   Source File: ShareTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void attemptConnection() {
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (device != null) {
        details.append("\nConnection state: " + " Device is not null");
        mConnectionState = mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT);
    }

    Log.w(TAG, "Connection state: " + mConnectionState);
    details.append("\nConnection state: " + mConnectionState);
    if (mConnectionState == STATE_DISCONNECTED || mConnectionState == STATE_DISCONNECTING) {
        ActiveBluetoothDevice btDevice = new Select().from(ActiveBluetoothDevice.class)
                .orderBy("_ID desc")
                .executeSingle();
        if (btDevice != null) {
            details.append("\nBT Device: " + btDevice.name);
            mDeviceName = btDevice.name;
            mDeviceAddress = btDevice.address;
            mBluetoothAdapter = mBluetoothManager.getAdapter();
            boolean newConnection = true;
            if(newConnection) {
                is_connected = connect(mDeviceAddress);
                details.append("\nConnecting...: ");
            }
        }
    }
}
 
Example 16
Source Project: SimpleBluetoothLeTerminal   Source File: SerialSocket.java    License: MIT License 6 votes vote down vote up
@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()
}
 
Example 17
Source Project: opentok-android-sdk-samples   Source File: CustomAudioDevice.java    License: MIT License 6 votes vote down vote up
private void forceConnectBluetooth() {
    /* force reconnection of bluetooth in the event of a phone call */
    Log.d("AUDIO_FOCUS", "Force Connect Bluetooth");
    synchronized (bluetoothLock) {
        if(getOutputType() == OutputType.BLUETOOTH) {
            bluetoothState = BluetoothState.DISCONNECTED;
            if (bluetoothAdapter != null) {
                bluetoothAdapter.getProfileProxy(
                    context,
                    bluetoothProfileListener,
                    BluetoothProfile.HEADSET
                );
            }
        }
    }
}
 
Example 18
@Override
public void onServerConnectionStateChange(BluetoothDevice device, int status, int newState) {
    Timber.d("[%s] Connection result %s", getDevice(), GattStatus.values()[status].name());
    TransactionResult.Builder builder = new TransactionResult.Builder().transactionName(getName());
    if(status == BluetoothGatt.GATT_SUCCESS) {
        if(newState == BluetoothProfile.STATE_CONNECTED) {
            getGattServer().setState(GattState.CONNECTED);
            builder.resultStatus(TransactionResult.TransactionResultStatus.SUCCESS)
                    .gattState(getGattServer().getGattState());
            callCallbackWithTransactionResultAndRelease(callback, builder.build());
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            getGattServer().setState(GattState.DISCONNECTED);
            builder.resultStatus(TransactionResult.TransactionResultStatus.FAILURE)
                    .gattState(getGattServer().getGattState());
            callCallbackWithTransactionResultAndRelease(callback, builder.build());
            getGattServer().setState(GattState.IDLE);
        }
    } else {
        getGattServer().setState(GattState.FAILURE_CONNECTING);
        builder.resultStatus(TransactionResult.TransactionResultStatus.FAILURE)
                .gattState(getGattServer().getGattState());
        callCallbackWithTransactionResultAndRelease(callback, builder.build());
        getGattServer().setState(GattState.DISCONNECTED);
    }
}
 
Example 19
Source Project: ibeacon-android-library   Source File: IBeaconProtocol.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Starts or stops the scanning process looking for iBeacons
 * @param enable <code>true</code> to start scanning, <code>false</code> to stop the scanning process
 */
public void scanIBeacons(final boolean enable) {
	if (enable) {
		// Stops scanning after a pre-defined scan period.
		_timeoutHandler = new Handler();
		_timeoutHandler.postDelayed(timeoutTask, IBeaconProtocol.SCANNING_PERIOD);

		_scanning = true;
		_arrOrderedIBeacons.clear();
		_bluetoothAdapter.startLeScan(mLeScanCallback);
		_listener.searchState(SEARCH_STARTED);
	} else {
		_scanning = false;
		_bluetoothAdapter.stopLeScan(mLeScanCallback);
		_listener.searchState(SEARCH_END_SUCCESS);
	}
	// Cannot obtain error status=133 this way
	Log.i(Utils.LOG_TAG,"The status:" + _bluetoothAdapter.getProfileConnectionState(BluetoothProfile.GATT));
}
 
Example 20
@Override
public void onServerConnectionStateChange(BluetoothDevice device, int status, int newState) {
    Timber.d("[%s] Gatt State %s, Disconnect Reason : %s", getDevice(), GattStatus.values()[status].name(),
            GattDisconnectReason.getReasonForCode(newState));
    TransactionResult.Builder builder = new TransactionResult.Builder().transactionName(getName());
    builder.responseStatus(GattDisconnectReason.getReasonForCode(status).ordinal());
    if (status == BluetoothGatt.GATT_SUCCESS) {
        if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            getGattServer().setState(GattState.DISCONNECTED);
            builder.gattState(getGattServer().getGattState())
                    .resultStatus(TransactionResult.TransactionResultStatus.SUCCESS);
            callCallbackWithTransactionResultAndRelease(callback, builder.build());
        } else if (newState == BluetoothProfile.STATE_CONNECTED) {
            getGattServer().setState(GattState.CONNECTED);
            builder.gattState(getGattServer().getGattState())
                    .resultStatus(TransactionResult.TransactionResultStatus.FAILURE);
            callCallbackWithTransactionResultAndRelease(callback, builder.build());
        }
    } else {
        builder.gattState(getGattServer().getGattState())
                .resultStatus(TransactionResult.TransactionResultStatus.FAILURE);
        callCallbackWithTransactionResultAndRelease(callback, builder.build());
    }
}
 
Example 21
Source Project: Easer   Source File: BTDeviceTracker.java    License: GNU General Public License v3.0 6 votes vote down vote up
BTDeviceTracker(Context context, BTDeviceUSourceData data,
                @NonNull PendingIntent event_positive,
                @NonNull PendingIntent event_negative) {
    super(context, data, event_positive, event_negative);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
        BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        for (int profile : new int[]{BluetoothProfile.GATT, BluetoothProfile.GATT_SERVER}) {
            for (BluetoothDevice btDevice : bluetoothManager.getConnectedDevices(profile)) {
                if (is_target(btDevice)) {
                    matched_devices++;
                }
            }
        }
    }
    determine_satisfied();
}
 
Example 22
private void onNativeConnectFail(final BluetoothDevice nativeDevice, final int gattStatus)
{
	//--- DRK > NOTE: Making an assumption that the underlying stack agrees that the connection state is STATE_DISCONNECTED.
	//---				This is backed up by basic testing, but even if the underlying stack uses a different value, it can probably
	//---				be assumed that it will eventually go to STATE_DISCONNECTED, so SweetBlue library logic is sounder "living under the lie" for a bit regardless.
	m_server.m_nativeWrapper.updateNativeConnectionState(nativeDevice.getAddress(), BluetoothProfile.STATE_DISCONNECTED);

	if( hasCurrentConnectTaskFor(nativeDevice) )
	{
		final P_Task_ConnectServer connectTask = m_queue.getCurrent(P_Task_ConnectServer.class, m_server);

		connectTask.onNativeFail(gattStatus);
	}
	else
	{
		m_server.onNativeConnectFail(nativeDevice, BleServer.ConnectionFailListener.Status.NATIVE_CONNECTION_FAILED_EVENTUALLY, gattStatus);
	}
}
 
Example 23
Source Project: sample-bluetooth-audio   Source File: A2dpSinkActivity.java    License: Apache License 2.0 6 votes vote down vote up
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(A2dpSinkHelper.ACTION_CONNECTION_STATE_CHANGED)) {
        int oldState = A2dpSinkHelper.getPreviousProfileState(intent);
        int newState = A2dpSinkHelper.getCurrentProfileState(intent);
        BluetoothDevice device = A2dpSinkHelper.getDevice(intent);
        Log.d(TAG, "Bluetooth A2DP sink changing connection state from " + oldState +
                " to " + newState + " device " + device);
        if (device != null) {
            String deviceName = Objects.toString(device.getName(), "a device");
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                speak("Connected to " + deviceName);
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                speak("Disconnected from " + deviceName);
            }
        }
    }
}
 
Example 24
Source Project: apollo-DuerOS   Source File: BtPairStateMachine.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean processMessage(Message msg) {
    switch(msg.what) {
        case EVENT_MD_READY:
            int connState = getHfpConnectionState();
            if (connState == BluetoothProfile.STATE_DISCONNECTED) {
                transitionTo(mPairDisconnectedState);
            } else if (connState == BluetoothProfile.STATE_CONNECTED) {
                deferMessage(obtainMessage(EVENT_CHECK_HFP_CONNECTION));
                transitionTo(mPairConnectedState);
            } else if (connState == BluetoothProfile.STATE_DISCONNECTING) {
                sendMessageDelayed(EVENT_MD_READY, 2000);
            } else if (connState == BluetoothProfile.STATE_CONNECTING) {
                sendMessageDelayed(EVENT_MD_READY, 2000);
            } else {
                deferMessage(obtainMessage(EVENT_ON_ERROR, ERROR_CHECK_CONNECTION, 0));
                transitionTo(mPairErrorState);
            }
            return HANDLED;
        default:
            return NOT_HANDLED;
    }
}
 
Example 25
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
   	Log.i(TAG, "on services discovered " + gatt.getDevice().getAddress() + " status = " + status);
     if (status == BluetoothGatt.GATT_SUCCESS) {
       	mDeviceInfo.setGatt(gatt);
        BTLEDeviceManager.this.mDeviceManagerCallback.onServicesDiscovered(mDeviceInfo.getDevice(), gatt);
    } else {
    	String error = String.format(mContext.getResources().getString(R.string.service_discovery_error), gatt.getDevice().getName(), status);
    	BTLEDeviceManager.this.mDeviceManagerCallback.onError(DeviceErrorCodes.ERROR_SERVICES_DISCOVERED, error, mDeviceInfo.getDeviceAddress());
    	try {
           	mDeviceInfo.setConnectionState(BluetoothProfile.STATE_DISCONNECTED);
            BTLEDeviceManager.this.disconnect(mDeviceInfo);
    	} catch (DeviceManagerException dmex) {
    		BTLEDeviceManager.this.mDeviceManagerCallback.onError(DeviceErrorCodes.ERROR_DISCONNECT, dmex.getMessage(), mDeviceInfo.getDeviceAddress());
    	}
    	// TODO: handle error
        Log.w(TAG, "onServicesDiscovered received: " + status);
    }
 	mDeviceInfo.executeNextCommand();
}
 
Example 26
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;
        broadcastUpdate(intentAction);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_GATT_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction);
    }
}
 
Example 27
Source Project: flutter-incall-manager   Source File: AppRTCBluetoothManager.java    License: ISC License 6 votes vote down vote up
/** Stops and closes all components related to Bluetooth audio. */
public void stop() {
  Log.d(TAG, "stop: BT state=" + bluetoothState);
  if (bluetoothAdapter == null) {
    return;
  }
  // Stop BT SCO connection with remote device if needed.
  stopScoAudio();
  // Close down remaining BT resources.
  if (bluetoothState == State.UNINITIALIZED) {
    return;
  }
  unregisterReceiver(bluetoothHeadsetReceiver);
  cancelTimer();
  if (bluetoothHeadset != null) {
    bluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, bluetoothHeadset);
    bluetoothHeadset = null;
  }
  bluetoothAdapter = null;
  bluetoothDevice = null;
  bluetoothState = State.UNINITIALIZED;
  Log.d(TAG, "stop done: BT state=" + bluetoothState);
}
 
Example 28
Source Project: gsn   Source File: UartService.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;
        mConnectionState = STATE_CONNECTED;
        broadcastUpdate(intentAction);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_GATT_DISCONNECTED;
        mConnectionState = STATE_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction);
    }
}
 
Example 29
Source Project: trigger   Source File: NukiCallback.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    //Log.i(TAG, "status: " + getGattStatus(status) + ", newState: " + newState);

    if (status == GATT_SUCCESS) {
        switch (newState) {
            case BluetoothProfile.STATE_CONNECTED:
                gatt.discoverServices();
                break;
            case BluetoothProfile.STATE_DISCONNECTED:
                closeConnection(gatt);
                break;
            case BluetoothProfile.STATE_CONNECTING:
            case BluetoothProfile.STATE_DISCONNECTING:
                break;
        }
    } else {
        closeConnection(gatt);
        this.listener.onTaskResult(
            setup_id, ReplyCode.REMOTE_ERROR, "Connection error: " + NukiRequestHandler.getGattStatus(status)
        );
    }
}
 
Example 30
Source Project: flutter-plugins   Source File: ESenseManager.java    License: MIT License 5 votes vote down vote up
@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);
        }
    }

}