android.bluetooth.BluetoothProfile Java Examples

The following examples show how to use android.bluetooth.BluetoothProfile. 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
Source File: BluetoothManager.java    From Linphone4Android with GNU General Public License v3.0 9 votes vote down vote up
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 File: BtPairStateMachine.java    From apollo-DuerOS with 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 #3
Source File: BluetoothLeService.java    From IoT-Firstep with 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;
        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 #4
Source File: UpdateService.java    From Android-nRF-Beacon-for-Eddystone with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #5
Source File: BluetoothLeService.java    From BLEConnect with GNU General Public License v2.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 #6
Source File: HidDataSender.java    From wearmouse with 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 File: BleManager.java    From BLEChat with 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 #8
Source File: UartService.java    From gsn with 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 #9
Source File: ShareTest.java    From xDrip-plus with 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 #10
Source File: NukiCallback.java    From trigger with 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 #11
Source File: BleUtils.java    From bleYan with 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 #12
Source File: UpdateService.java    From Android-nRF-Beacon with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #13
Source File: ParserUtils.java    From Android-BLE-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #14
Source File: BTLEDeviceManager.java    From BLEService with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #15
Source File: AppRTCBluetoothManager.java    From flutter-incall-manager with 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 #16
Source File: ACSUtilityService.java    From ESeal with 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 #17
Source File: BluetoothPeripheral.java    From blessed-android with 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 #18
Source File: BluetoothManager.java    From Linphone4Android with GNU General Public License v3.0 6 votes vote down vote up
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 #19
Source File: ShareTest.java    From xDrip with 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 #20
Source File: SerialSocket.java    From SimpleBluetoothLeTerminal with 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 #21
Source File: CustomAudioDevice.java    From opentok-android-sdk-samples with 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 #22
Source File: GattServerConnectTransaction.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
@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 #23
Source File: IBeaconProtocol.java    From ibeacon-android-library with 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 #24
Source File: GattServerDisconnectTransaction.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
@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 #25
Source File: BTDeviceTracker.java    From Easer with 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 #26
Source File: A2dpSinkActivity.java    From sample-bluetooth-audio with 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 #27
Source File: BluetoothLeService.java    From IoT-Firstep with 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;
        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 #28
Source File: MyBleService.java    From science-journal with 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 #29
Source File: GattServerDisconnectMockTransaction.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void transaction(GattTransactionCallback callback) {
    this.callback = callback;
    getGattServer().setState(GattState.DISCONNECTING);
    mainHandler.postDelayed(() -> {
        if (shouldFail) {
            onServerConnectionStateChange(null, BluetoothGatt.GATT_FAILURE, BluetoothProfile.STATE_CONNECTED);
        } else {
            onServerConnectionStateChange(null, BluetoothGatt.GATT_SUCCESS, BluetoothProfile.STATE_DISCONNECTED);
        }
    }, REASONABLE_AMOUNT_OF_TIME_FOR_DISCONNECT);
}
 
Example #30
Source File: AbstractHOGPServer.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
@Override
public void onConnectionStateChange(final BluetoothDevice device, final int status, final int newState) {
    if (DEBUG) {
        Log.d(TAG, "onConnectionStateChange status: " + status + ", newState: " + newState);
    }

    if (mGattServer == null) {
        return;
    }

    switch (newState) {
        case BluetoothProfile.STATE_CONNECTED:
            if (DEBUG) {
                Log.d(TAG, "BluetoothProfile.STATE_CONNECTED bondState: " + device.getBondState());
            }

            // check bond status
            if (device.getBondState() == BluetoothDevice.BOND_NONE) {
                paringDevice(device);
            } else if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                connectDevice(device);
            }
            break;

        case BluetoothProfile.STATE_DISCONNECTED:
            if (DEBUG) {
                Log.w(TAG, "BluetoothProfile.STATE_DISCONNECTED");
            }
            disconnectDevice(device);
            break;

        default:
            // do nothing
            break;
    }
}