Java Code Examples for android.bluetooth.BluetoothProfile#STATE_DISCONNECTED

The following examples show how to use android.bluetooth.BluetoothProfile#STATE_DISCONNECTED . 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: ShareTest.java    From xDrip 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) {
        mBluetoothGatt = gatt;
        mConnectionState = STATE_CONNECTED;
        ActiveBluetoothDevice.connected();
        Log.w(TAG, "Connected to GATT server.");
        Log.w(TAG, "Connection state: Bonded - " + device.getBondState());

        if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
            currentGattTask = GATT_SETUP;
            mBluetoothGatt.discoverServices();

        } else {
            device.setPin("000000".getBytes());
            device.createBond();
        }
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        mConnectionState = STATE_DISCONNECTED;
        ActiveBluetoothDevice.disconnected();
        Log.w(TAG, "Disconnected from GATT server.");
    }
}
 
Example 2
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 3
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 4
Source File: BluetoothLeService.java    From android-BluetoothLeGatt with Apache License 2.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 5
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 6
Source File: BLEPeripheralDefault.java    From itag with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(@NonNull BluetoothGatt gatt, int status, int newState) {
    if (BuildConfig.DEBUG) {
        Log.d(LT, "onConnectionStateChange id=" + identifier() +
                " addr=" + gatt.getDevice().getAddress() +
                " status=" + status +
                " newState=" + newState);
    }
    if (status == GATT_SUCCESS) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            setGatt(gatt);
            setState(BLEPeripheralState.connected);
            observables.channelConnected.broadcast(new BLEPeripheralObservablesInterface.ConnectedEvent());
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            close();
            observables.channelDisconnected.broadcast(new BLEPeripheralObservablesInterface.DisconnectedEvent(status));
        }
    } else {
        close();
        if (getState() == BLEPeripheralState.connecting) {
            observables.channelConnectionFailed.broadcast(new BLEPeripheralObservablesInterface.ConnectionFailedEvent(status));
        } else {
            observables.channelDisconnected.broadcast(new BLEPeripheralObservablesInterface.DisconnectedEvent(status));
        }
    }
}
 
Example 7
Source File: BluetoothPeripheral.java    From blessed-android with MIT License 6 votes vote down vote up
/**
 * Try to connect to a device whenever it is found by the OS. This call never times out.
 * Connecting to a device will take longer than when using connect()
 */
void autoConnect() {
    // Note that this will only work for devices that are known! After turning BT on/off Android doesn't know the device anymore!
    // https://stackoverflow.com/questions/43476369/android-save-ble-device-to-reconnect-after-app-close
    if (state == BluetoothProfile.STATE_DISCONNECTED) {
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                // Connect to device with autoConnect = true
                Timber.i("autoConnect to '%s' (%s) using TRANSPORT_LE", getName(), getAddress());
                registerBondingBroadcastReceivers();
                state = BluetoothProfile.STATE_CONNECTING;
                bluetoothGatt = connectGattHelper(device, true, bluetoothGattCallback);
                connectTimestamp = SystemClock.elapsedRealtime();
            }
        });
    } else {
        Timber.e("peripheral '%s' not yet disconnected, will not connect", getName());
    }
}
 
Example 8
Source File: DeviceActivity.java    From BLERW with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
		int newState) {
	if (newState == BluetoothProfile.STATE_CONNECTED) {
		mStatus = newState;
		mConnGatt.discoverServices();
	} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
		mStatus = newState;
		runOnUiThread(new Runnable() {
			public void run() {
				mReadManufacturerNameButton.setEnabled(false);
				mReadSerialNumberButton.setEnabled(false);
				mWriteAlertLevelButton.setEnabled(false);
			};
		});
	}
}
 
Example 9
Source File: BluetoothLeService.java    From SensorTag-CC2650 with Apache License 2.0 6 votes vote down vote up
/**
 * Disconnects an existing connection or cancel a pending connection. The
 * disconnection result is reported asynchronously through the
 * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
 * callback.
 */
public void disconnect(String address) {
	if (mBtAdapter == null) {
		// Log.w(TAG, "disconnect: BluetoothAdapter not initialized");
		return;
	}
	final BluetoothDevice device = mBtAdapter.getRemoteDevice(address);
	int connectionState = mBluetoothManager.getConnectionState(device,
	    BluetoothProfile.GATT);

	if (mBluetoothGatt != null) {
		if (connectionState != BluetoothProfile.STATE_DISCONNECTED) {
			mBluetoothGatt.disconnect();
		} else {
			// Log.w(TAG, "Attempt to disconnect in state: " + connectionState);
		}
	}
}
 
Example 10
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;
    }
}
 
Example 11
Source File: BluetoothLeService.java    From SensorTag-CC2650 with Apache License 2.0 5 votes vote down vote up
/**
 * Connects to the GATT server hosted on the Bluetooth LE device.
 * 
 * @param address
 *          The device address of the destination device.
 * 
 * @return Return true if the connection is initiated successfully. The
 *         connection result is reported asynchronously through the
 *         {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
 *         callback.
 */
public boolean connect(final String address) {
	if (mBtAdapter == null || address == null) {
		// Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
		return false;
	}
	final BluetoothDevice device = mBtAdapter.getRemoteDevice(address);
       this.mDevicePrefs = new PreferenceWR(device.getAddress(),this.getApplicationContext());
	int connectionState = mBluetoothManager.getConnectionState(device,
               BluetoothProfile.GATT);

	if (connectionState == BluetoothProfile.STATE_DISCONNECTED) {

		// Previously connected device. Try to reconnect.
		if (mBluetoothDeviceAddress != null
		    && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) {
			// Log.d(TAG, "Re-use GATT connection");
			if (mBluetoothGatt.connect()) {
				return true;
			} else {
				// Log.w(TAG, "GATT re-connect failed.");
				return false;
			}
		}

		if (device == null) {
			// Log.w(TAG, "Device not found.  Unable to connect.");
			return false;
		}
		// We want to directly connect to the device, so we are setting the
		// autoConnect parameter to false.
		// Log.d(TAG, "Create a new GATT connection.");
		mBluetoothGatt = device.connectGatt(this, false, mGattCallbacks);
		mBluetoothDeviceAddress = address;
	} else {
		// Log.w(TAG, "Attempt to connect in state: " + connectionState);
		return false;
	}
	return true;
}
 
Example 12
Source File: MkrSciBleManager.java    From science-journal with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
  if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
    this.gatt = gatt;
    characteristics.clear();
    gatt.discoverServices();
  } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
    readyForAction = false;
    gatt.disconnect();
  }
}
 
Example 13
Source File: ESenseManager.java    From flutter-plugins with 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);
        }
    }

}
 
Example 14
Source File: BTLEDeviceManager.java    From BLEService with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public BTDeviceInfo(BluetoothDevice device) {
	mDevice = device;
	mGatt = null;
	mConnectionState = BluetoothProfile.STATE_DISCONNECTED;
	mfDisconnectRequest = false;
	mRetryCount = MAX_RETRY_COUNT;
	mCommandQueue = new ArrayDeque<BTLECommand>();
	mConnTimeout = null;
	mConnTimeoutMsec = 0;
	mfRetrying = false;
}
 
Example 15
Source File: GattServerActivity.java    From sample-bluetooth-le-gattserver with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        Log.i(TAG, "BluetoothDevice CONNECTED: " + device);
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        Log.i(TAG, "BluetoothDevice DISCONNECTED: " + device);
        //Remove device from any active subscriptions
        mRegisteredDevices.remove(device);
    }
}
 
Example 16
Source File: BluetoothLeService.java    From BlunoBasicDemo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    System.out.println("BluetoothGattCallback----onConnectionStateChange"+newState);
    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.
        if(mBluetoothGatt.discoverServices())
        {
            Log.i(TAG, "Attempting to start service discovery:");

        }
        else{
            Log.i(TAG, "Attempting to start service discovery:not success");

        }


    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_GATT_DISCONNECTED;
        mConnectionState = STATE_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction);
    }
}
 
Example 17
Source File: UpdateFragment.java    From Android-nRF-Beacon-for-Eddystone with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void updateUiForBeacons(int connectionState, int lockState) {
    switch (connectionState) {
        case BluetoothProfile.STATE_CONNECTED:
            if (UpdateService.LOCKED == lockState) {
                mIsBeaconLocked = true;
                mCurrentLockState = LOCKED;
            } else if(UpdateService.UNLOCKED == lockState || UpdateService.UNLOCKED_AUTOMATIC_RELOCK_DISABLED == lockState) {
                mChallenge = null; //setting the challenge to a null or else the user will be prompted with a unlock failure message
                mCurrentLockState = lockState;
                mIsBeaconLocked = false;
                mBeaconHelp.setVisibility(View.GONE);
                mBeaconConfigurationContainer.setVisibility(View.VISIBLE);
                mFrameTypeContainer.setVisibility(View.VISIBLE);
            }
            break;
        case BluetoothProfile.STATE_DISCONNECTED:
            setHasOptionsMenu(false);
            getActivity().invalidateOptionsMenu();
            if(mClearActiveSlot != null) {
                mClearActiveSlot.setImageBitmap(null);
                mClearActiveSlot = null;
            }
            if(mRefreshActiveSlot != null) {
                mRefreshActiveSlot.setImageBitmap(null);
                mRefreshActiveSlot = null;
            }
            mBeaconHelp.setVisibility(View.VISIBLE);
            mBeaconConfigurationContainer.setVisibility(View.GONE);
            mFrameTypeContainer.setVisibility(View.GONE);
            //clear all resources on disconnection
            mBeaconPublicEcdhKey = null;
            mDecryptedIdentityKey = null;
            mServiceEcdhKey = null;
            mIsBeaconLocked = true;
            if(mActiveSlotsTypes != null) {
                mActiveSlotsTypes.clear();
            }
            if(mMaxActiveSlotsAdapter != null){
                mMaxActiveSlotsAdapter.clear();
                mMaxActiveSlotsAdapter = null;
            }
            break;
    }
}
 
Example 18
Source File: BluetoothPeripheral.java    From blessed-android with MIT License 4 votes vote down vote up
@Override
public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
    long timePassed = SystemClock.elapsedRealtime() - connectTimestamp;
    cancelConnectionTimer();
    final int previousState = state;
    state = newState;

    if (status == GATT_SUCCESS) {
        switch (newState) {
            case BluetoothProfile.STATE_CONNECTED:
                successfullyConnected(device.getBondState(), timePassed);
                break;
            case BluetoothProfile.STATE_DISCONNECTED:
                successfullyDisconnected(previousState);
                break;
            case BluetoothProfile.STATE_DISCONNECTING:
                Timber.i("peripheral is disconnecting");
                break;
            case BluetoothProfile.STATE_CONNECTING:
                Timber.i("peripheral is connecting");
            default:
                Timber.e("unknown state received");
                break;
        }
    } else {
        connectionStateChangeUnsuccessful(status, previousState, newState, timePassed);
    }
}
 
Example 19
Source File: DeviceActivity.java    From BLERW with Apache License 2.0 4 votes vote down vote up
private void init() {
	// BLE check
	if (!BleUtil.isBLESupported(this)) {
		Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT)
				.show();
		finish();
		return;
	}

	// BT check
	BluetoothManager manager = BleUtil.getManager(this);
	if (manager != null) {
		mBTAdapter = manager.getAdapter();
	}
	if (mBTAdapter == null) {
		Toast.makeText(this, R.string.bt_unavailable, Toast.LENGTH_SHORT)
				.show();
		finish();
		return;
	}

	// check BluetoothDevice
	if (mDevice == null) {
		mDevice = getBTDeviceExtra();
		if (mDevice == null) {
			finish();
			return;
		}
	}

	// button disable
	mReadManufacturerNameButton.setEnabled(false);
	mReadSerialNumberButton.setEnabled(false);
	mWriteAlertLevelButton.setEnabled(false);

	// connect to Gatt
	if ((mConnGatt == null)
			&& (mStatus == BluetoothProfile.STATE_DISCONNECTED)) {
		// try to connect
		mConnGatt = mDevice.connectGatt(this, false, mGattcallback);
		mStatus = BluetoothProfile.STATE_CONNECTING;
	} else {
		if (mConnGatt != null) {
			// re-connect and re-discover Services
			mConnGatt.connect();
			mConnGatt.discoverServices();
		} else {
			Log.e(TAG, "state error");
			finish();
			return;
		}
	}
	setProgressBarIndeterminateVisibility(true);
}
 
Example 20
Source File: DexShareCollectionService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    Log.i(TAG, "Gatt state change status: " + status + " new state: " + newState);
    if (status == 133) {
        statusErrors++;
        Log.e(TAG, "Got the status 133 bug, bad news! count:"+statusErrors+" - Might require devices to forget each other: instance uptime: "+JoH.qs((JoH.ts()-instance)/1000,0));
        if (statusErrors>4)
        {
            Log.wtf(TAG,"Forcing bluetooth reset to try to combat errors");
            statusErrors=0;
            JoH.niceRestartBluetooth(getApplicationContext());
            setRetryTimer();
            close();
            stopSelf();
            return;
        }
    }
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        mBluetoothGatt = gatt;
        device = mBluetoothGatt.getDevice();
        mConnectionState = STATE_CONNECTED;
        ActiveBluetoothDevice.connected();
        Log.i(TAG, "Connected to GATT server.");

        Log.i(TAG, "discovering services");
        currentGattTask = GATT_SETUP;
        if (mBluetoothGatt == null || !mBluetoothGatt.discoverServices()) {
            Log.w(TAG, "discovering failed");
            if(shouldDisconnect) {
                stopSelf();
            } else {
                setRetryTimer();
            }
        }
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        mConnectionState = STATE_DISCONNECTED;
        ActiveBluetoothDevice.disconnected();
        if(shouldDisconnect) {
            stopSelf();
        } else {
            setRetryTimer();
        }
        Log.d(TAG, "Disconnected from GATT server.");
    } else {
        Log.d(TAG, "Gatt callback... strange state.");
    }
}