Java Code Examples for android.bluetooth.BluetoothDevice

The following examples show how to use android.bluetooth.BluetoothDevice. 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
Source Project: EFRConnect-android   Source File: BrowserActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
    protected void onDestroy() {
        super.onDestroy();

        bluetoothBinding = new BlueToothService.Binding(getApplicationContext()) {
            @Override
            protected void onBound(BlueToothService service) {
                for (BluetoothDevice bd : getConnectedBluetoothDevices()) {
                    service.disconnectGatt(bd.getAddress());
                }
                service.clearGatt();
                bluetoothBinding.unbind();
            }
        };
        BlueToothService.bind(bluetoothBinding);

//        Log.d("onDestroy", "Called");
//        if (bluetoothBinding != null) {
//            bluetoothBinding.unbind();
//        }
        discovery.disconnect();
    }
 
Example 2
@Override
public void onIntermediateCuffPressureReceived(@NonNull final BluetoothDevice device, final float cuffPressure, final int unit,
											   @Nullable final Float pulseRate, @Nullable final Integer userID,
											   @Nullable final BPMStatus status, @Nullable final Calendar calendar) {
	runOnUiThread(() -> {
		systolicView.setText(String.valueOf(cuffPressure));
		diastolicView.setText(R.string.not_available_value);
		meanAPView.setText(R.string.not_available_value);
		if (pulseRate != null)
			pulseView.setText(String.valueOf(pulseRate));
		else
			pulseView.setText(R.string.not_available_value);
		if (calendar != null)
			timestampView.setText(getString(R.string.bpm_timestamp, calendar));
		else
			timestampView.setText(R.string.not_available);

		systolicUnitView.setText(unit == IntermediateCuffPressureCallback.UNIT_mmHg ? R.string.bpm_unit_mmhg : R.string.bpm_unit_kpa);
		diastolicUnitView.setText(null);
		meanAPUnitView.setText(null);
	});
}
 
Example 3
@Override
public void onPeripheralFound(BluetoothDevice device, ScanResult scanResult) {

    Log.d(TAG, "====== onPeripheralFound ===== " + device.getName());
    boolean deviceExists = false;
    String serviceUuid = "";

    if (scanResult.getScanRecord().getServiceUuids() != null && scanResult.getScanRecord().getServiceUuids().size() > 0) {
        serviceUuid = scanResult.getScanRecord().getServiceUuids().get(0).toString();
    }
    Log.d(TAG, "Add service UUID : " + serviceUuid);

    if (bluetoothDevices.containsKey(device)) {
        deviceExists = true;
    }

    if (!deviceExists) {
        listView.setVisibility(View.VISIBLE);
        bluetoothDevices.put(device, serviceUuid);
        deviceList.add(device);
        adapter.notifyDataSetChanged();
    }
}
 
Example 4
@Override
public void onDescriptorRead(final BluetoothGatt gatt, final BluetoothGattDescriptor descriptor, final int status) {
	if (status == BluetoothGatt.GATT_SUCCESS) {
		// The value has been read. Notify the profile and proceed with the initialization queue.
		profile.onDescriptorRead(gatt, descriptor);
		operationInProgress = false;
		nextRequest();
	} else if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
		if (gatt.getDevice().getBondState() != BluetoothDevice.BOND_NONE) {
			// This should never happen but it used to: http://stackoverflow.com/a/20093695/2115352
			DebugLogger.w(TAG, ERROR_AUTH_ERROR_WHILE_BONDED);
			onError(gatt.getDevice(), ERROR_AUTH_ERROR_WHILE_BONDED, status);
		}
	} else {
		DebugLogger.e(TAG, "onDescriptorRead error " + status);
		onError(gatt.getDevice(), ERROR_READ_DESCRIPTOR, status);
	}
}
 
Example 5
Source Project: libcommon   Source File: BluetoothManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
	 * Bluetooth機器の探索を開始する。
	 * bluetoothに対応していないか無効になっている時はIllegalStateException例外を投げる
	 * 新しく機器が見つかった時はBluetoothDevice.ACTION_FOUNDがブロードキャストされるので
	 * ブロードキャストレシーバーを登録しておく必要がある
	 * @throws IllegalStateException
	 */
	public void startDiscovery() throws IllegalStateException {
//		if (DEBUG) Log.v(TAG, "startDiscovery:");
		synchronized (mSync) {
			if (mAdapter.isDiscovering()) {
				// 既に探索中なら一旦キャンセルする
				mAdapter.cancelDiscovery();
			}
			// 既にペアリング済みのBluetooth機器一覧を取得する
			final Set<BluetoothDevice> pairedDevices = mAdapter.getBondedDevices();
			synchronized (mDiscoveredDeviceList) {
				mDiscoveredDeviceList.clear();
				if (pairedDevices.size() > 0) {
					for (final BluetoothDevice device : pairedDevices) {
						mDiscoveredDeviceList.add(new BluetoothDeviceInfo(device));
					}
					callOnDiscover();
				}
			}
//			if (DEBUG) Log.v(TAG, "startDiscovery:探索開始");
			mAdapter.startDiscovery();
		}
	}
 
Example 6
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
	super.onDataReceived(device, data);

	final Integer offset = readTimeZone(data, 0);
	if (offset == null) {
		onInvalidDataReceived(device, data);
		return;
	}

	if (offset == -128) {
		onUnknownTimeZoneReceived(device);
	} else if (offset < -48 || offset > 56) {
		onInvalidDataReceived(device, data);
	} else {
		onTimeZoneReceived(device, offset * 15);
	}
}
 
Example 7
Source Project: Android-BLE-Terminal   Source File: DeviceListActivity.java    License: MIT License 6 votes vote down vote up
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    addDevice(device, rssi);
                }
            });

        }
    });
}
 
Example 8
Source Project: AndroidDemo   Source File: BluetoothMainActivity.java    License: MIT License 6 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RequestBluetoothCode) {
        if (resultCode == RESULT_OK) {
            Set<BluetoothDevice> set = bluetoothAdapter.getBondedDevices();
            bondedDevices.clear();
            for (BluetoothDevice device : set) {
                bondedDevices.add(device);
                String text = device.getName() + " address: " + device.getAddress() + " type: " + device.getType() + "\n";
                tv_detail.append(text);
            }
        } else
            Toast.makeText(this, "Open Bluetooth is failed,please open in Setting.", Toast.LENGTH_SHORT).show();
    } else
        super.onActivityResult(requestCode, resultCode, data);
}
 
Example 9
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 10
/**
 * Sends the request to obtain from the glucose device all records newer than the newest one
 * from local storage. The data will be returned to Glucose Measurement characteristic as
 * a notification followed by Record Access Control Point indication with status code Success
 * or other in case of error.
 * <p>
 * Refresh button will not download records older than the oldest in the local memory.
 * E.g. if you have pressed Last and then Refresh, than it will try to get only newer records.
 * However if there are no records, it will download all existing (using {@link #getAllRecords()}).
 */
void refreshRecords() {
	if (recordAccessControlPointCharacteristic == null)
		return;
	final BluetoothDevice target = getBluetoothDevice();
	if (target == null)
		return;

	if (records.size() == 0) {
		getAllRecords();
	} else {
		mCallbacks.onOperationStarted(target);

		// obtain the last sequence number
		final int sequenceNumber = records.keyAt(records.size() - 1) + 1;

		writeCharacteristic(recordAccessControlPointCharacteristic,
				RecordAccessControlPointData.reportStoredRecordsGreaterThenOrEqualTo(sequenceNumber))
				.with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" sent"))
				.enqueue();
		// Info:
		// Operators OPERATOR_LESS_THEN_OR_EQUAL and OPERATOR_RANGE are not supported by Nordic Semiconductor Glucose Service in SDK 4.4.2.
	}
}
 
Example 11
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    Log.d(TAG, "characteristic wrote " + status);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        Log.d(TAG, "Wrote a characteristic successfully " + characteristic.getUuid());
        if (mAuthenticationCharacteristic.getUuid().equals(characteristic.getUuid())) {
            state_authSucess = true;
            gatt.readCharacteristic(mHeartBeatCharacteristic);
        }
    } else if ((status & BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) != 0 || (status & BluetoothGatt.GATT_INSUFFICIENT_ENCRYPTION) != 0) {
        if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_NONE) {
            device = gatt.getDevice();
            state_authInProgress = true;
            bondDevice();
        } else {
            Log.e(TAG, "The phone is trying to read from paired device without encryption. Android Bug? Have the dexcom forget whatever device it was previously paired to");
        }
    } else {
        Log.e(TAG, "Unknown error writing Characteristic");
    }
}
 
Example 12
@Override
public void onStart() {
    super.onStart();
   
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
}
 
Example 13
@Override
public void onReceive(final Context context, final Intent intent) {
    final BluetoothDevice device = intent.getParcelableExtra(EXTRA_DEVICE);
    switch (intent.getAction()) {
        case ACTION_FIND:
            binder.log(device, LogContract.Log.Level.INFO, "[Notification] FIND action pressed");
            break;
        case ACTION_SILENT:
            binder.log(device, LogContract.Log.Level.INFO, "[Notification] SILENT action pressed");
            break;
    }
    binder.toggleImmediateAlert(device);
}
 
Example 14
Source Project: tilt-game-android   Source File: BluetoothServerService.java    License: MIT License 5 votes vote down vote up
@Override
protected BluetoothCommunicationThread createCommunicationThread(BluetoothSocket socket, BluetoothDevice device) {
    BluetoothCommunicationThread communicationThread = super.createCommunicationThread(socket, device);

    _communicationThreads.put(device.getAddress(), communicationThread);

    return communicationThread;
}
 
Example 15
Source Project: AsteroidOSSync   Source File: BleManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
final P_NativeDeviceLayer newNativeDevice(final String macAddress)
{
	BluetoothDevice nativeDevice = managerLayer().getRemoteDevice(macAddress);
	P_NativeDeviceLayer layer = m_config.newDeviceLayer(BleDevice.NULL);
	layer.setNativeDevice(nativeDevice);
	return layer;
}
 
Example 16
public BluetoothDevice getDevice()
{
	if( m_device.isNull() )
	{
		return m_device.getManager().newNativeDevice(BleDevice.NULL_MAC()).getNativeDevice();
	}
	else
	{
		return m_device_native.getNativeDevice();
	}
}
 
Example 17
Source Project: xDrip   Source File: Helper.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String bondStateToString(final int bs) {
    String bondState;
    if (bs == BluetoothDevice.BOND_NONE) {
        bondState = "Unpaired";
    } else if (bs == BluetoothDevice.BOND_BONDING) {
        bondState = "Pairing";
    } else if (bs == BluetoothDevice.BOND_BONDED) {
        bondState = "Paired";
    } else if (bs == 0) {
        bondState = "Startup";
    } else {
        bondState = "Unknown bond state: " + bs;
    }
    return bondState;
}
 
Example 18
Source Project: Android-BLE-Terminal   Source File: DeviceListActivity.java    License: MIT License 5 votes vote down vote up
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    BluetoothDevice device = deviceList.get(position);
    mBluetoothAdapter.stopLeScan(mLeScanCallback);

    Bundle b = new Bundle();
    b.putString(BluetoothDevice.EXTRA_DEVICE, deviceList.get(position).getAddress());

    Intent result = new Intent();
    result.putExtras(b);
    setResult(Activity.RESULT_OK, result);
    showMessage(deviceList.get(position).getAddress());
    finish();
}
 
Example 19
Source Project: BLEChat   Source File: BleManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
public boolean connectGatt(Context c, boolean bAutoReconnect, String address) {
	if(c == null || address == null)
		return false;
	
	if(mBluetoothGatt != null && mDefaultDevice != null
			&& address.equals(mDefaultDevice.getAddress())) {
		 if (mBluetoothGatt.connect()) {
			 mState = STATE_CONNECTING;
			 return true;
		 }
	}
	
	BluetoothDevice device = 
			BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
	if (device == null) {
		Logs.d("# Device not found.  Unable to connect.");
		return false;
	}
	
	mGattServices.clear();
	mGattCharacteristics.clear();
	mWritableCharacteristics.clear();
	
	mBluetoothGatt = device.connectGatt(c, bAutoReconnect, mGattCallback);
	mDefaultDevice = device;
	
	mState = STATE_CONNECTING;
	mHandler.obtainMessage(MESSAGE_STATE_CHANGE, STATE_CONNECTING, 0).sendToTarget();
	return true;
}
 
Example 20
Source Project: BlueToothEatPhone   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void initDate() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        /**注册搜索蓝牙receiver*/
        mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        mFilter.addAction(BluetoothDevice.ACTION_FOUND);
        mFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(mReceiver, mFilter);
        /**注册配对状态改变监听器*/
//        IntentFilter mFilter = new IntentFilter();
//        mFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
//        mFilter.addAction(BluetoothDevice.ACTION_FOUND);
//        registerReceiver(mReceiver, mFilter);

        getBondedDevices();
    }
 
Example 21
private void setupBluetoothBroadcastReceiver(){
    String[] actions = new String[4];
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        actions[0] = BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED;
    }else{
        actions[0] = "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED";
    }
    actions[1] = BluetoothAdapter.ACTION_STATE_CHANGED;
    actions[2] = BluetoothDevice.ACTION_ACL_DISCONNECTED;
    actions[3] = BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED;

    listenForIntents(actions);
}
 
Example 22
private void a(BluetoothDevice bluetoothdevice)
{
    o = bluetoothdevice;
    Utils.connect(bluetoothdevice, false);
    h.sendEmptyMessage(4097);
    h.sendEmptyMessageDelayed(4115, 60000L);
    UmengAnalytics.startEvent(l, "StartUpConnectBracelet");
}
 
Example 23
Source Project: blue-pair   Source File: BluetoothController.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the status of the current pairing and cleans up the state if the pairing is done.
 *
 * @return the current pairing status.
 * @see BluetoothDevice#getBondState()
 */
public int getPairingDeviceStatus() {
    if (this.boundingDevice == null) {
        throw new IllegalStateException("No device currently bounding");
    }
    int bondState = this.boundingDevice.getBondState();
    // If the new state is not BOND_BONDING, the pairing is finished, cleans up the state.
    if (bondState != BluetoothDevice.BOND_BONDING) {
        this.boundingDevice = null;
    }
    return bondState;
}
 
Example 24
@Override
public void onBonded(@NonNull final BluetoothDevice device) {
    showToast(no.nordicsemi.android.nrftoolbox.common.R.string.bonded);

    final Intent broadcast = new Intent(BROADCAST_BOND_STATE);
    broadcast.putExtra(EXTRA_DEVICE, bluetoothDevice);
    broadcast.putExtra(EXTRA_BOND_STATE, BluetoothDevice.BOND_BONDED);
    LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast);
}
 
Example 25
Source Project: NewXmPluginSDK   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
@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) {
    }
}
 
Example 26
@Test
public void onTemperatureMeasurementReceived() {
	final ProfileReadResponse response = new TemperatureMeasurementDataCallback() {
		@Override
		public void onTemperatureMeasurementReceived(@NonNull final BluetoothDevice device,
													 final float temperature, final int unit,
													 @Nullable final Calendar calendar,
													 @Nullable final Integer type) {
			called = true;
			assertEquals("Temperature", 37.60f, temperature, 0.001f);
			assertEquals("Unit", TemperatureMeasurementCallback.UNIT_C, unit);
			assertNotNull("Calendar present", calendar);
			assertTrue("Year set", calendar.isSet(Calendar.YEAR));
			assertEquals("Year", calendar.get(Calendar.YEAR), 2012);
			assertTrue("Month set", calendar.isSet(Calendar.MONTH));
			assertEquals("Month", calendar.get(Calendar.MONTH), Calendar.DECEMBER);
			assertTrue("Day set", calendar.isSet(Calendar.DATE));
			assertEquals("Day", 5, calendar.get(Calendar.DATE));
			assertEquals("Hour", 11, calendar.get(Calendar.HOUR_OF_DAY));
			assertEquals("Minute", 50, calendar.get(Calendar.MINUTE));
			assertEquals("Seconds", 27, calendar.get(Calendar.SECOND));
			assertEquals("Milliseconds", 0, calendar.get(Calendar.MILLISECOND));
			assertNotNull("Type present", type);
			assertEquals(TemperatureMeasurementCallback.TYPE_FINGER, type.intValue());
		}
	};

	final Data data = new Data(new byte[] { 0x06, (byte) 0xB0, 0x0E, 0x00, (byte) 0xFE, (byte) 0xDC, 0x07, 0x0C, 0x05, 0x0B, 0x32, 0x1B, 0x04 });
	called = false;
	response.onDataReceived(null, data);
	assertTrue(called);
	assertTrue(response.isValid());
}
 
Example 27
private void unpairBluetoothDevices(Set<BluetoothDevice> bondedDevices) {
    try {
        for (BluetoothDevice device : bondedDevices) {
            unpairBluetoothDevice(device);
        }
        setResultCode(Activity.RESULT_OK);
    } catch (Exception e) {
        String message = String.format("Unpairing bluetooth devices failed with exception: %s", e.getMessage());
        Log.e(TAG, message);
        setResultCode(Activity.RESULT_CANCELED);
        setResultData(message);
    }
}
 
Example 28
Source Project: cordova-plugin-datecs-printer   Source File: DatecsSDKWrapper.java    License: MIT License 5 votes vote down vote up
/**
 * Cria um socket Bluetooth
 *
 * @param device
 * @param uuid
 * @param callbackContext
 * @return BluetoothSocket
 * @throws IOException
 */
private BluetoothSocket createBluetoothSocket(BluetoothDevice device, UUID uuid, final CallbackContext callbackContext) throws IOException {
    try {
        Method method = device.getClass().getMethod("createRfcommSocketToServiceRecord", new Class[] { UUID.class });
        return (BluetoothSocket) method.invoke(device, uuid);
    } catch (Exception e) {
        e.printStackTrace();
        sendStatusUpdate(false);
        callbackContext.error(this.getErrorByCode(19));
        showError(DatecsUtil.getStringFromStringResource(app, "failed_to_comm") + ": " + e.getMessage(), false);
    }
    return device.createRfcommSocketToServiceRecord(uuid);
}
 
Example 29
Source Project: apollo-DuerOS   Source File: BtUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * a wrapper method for {@link BluetoothDevice#setPairingConfirmation(boolean)}
 * @param btClass if the platform is lower than 19, btClass is used to reflect BluetoothDevice to invoke setPairingConfirmation()
 * @param btDevice if the platform is 19 or higher, btDevice is used to invoke setPairingConfirmation()
 * @param confirm whether to confirm passkey
 * @return true confirmation has been sent out
 *         false for error
 * @throws Exception
 */
@SuppressLint("NewApi")
public static boolean setPairingConfirmation(Class<?> btClass, BluetoothDevice btDevice,
        boolean confirm) throws Exception {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        return btDevice.setPairingConfirmation(confirm);
    } else {
        Method setPairingConfirmationMethod = btClass.getDeclaredMethod("setPairingConfirmation",
                new Class[] {boolean.class});
        Boolean returnValue = (Boolean) setPairingConfirmationMethod.invoke(btDevice, confirm);
        return returnValue.booleanValue();
    }
}
 
Example 30
@Override
public void onHeartRateMeasurementReceived(@NonNull final BluetoothDevice device,
										   final int heartRate,
										   @Nullable final Boolean contactDetected,
										   @Nullable final Integer energyExpanded,
										   @Nullable final List<Integer> rrIntervals) {
	HeartRateMeasurementDataCallbackTest.this.success = true;
	HeartRateMeasurementDataCallbackTest.this.heartRate = heartRate;
	HeartRateMeasurementDataCallbackTest.this.contactDetected = contactDetected;
	HeartRateMeasurementDataCallbackTest.this.energyExpanded = energyExpanded;
	HeartRateMeasurementDataCallbackTest.this.rrIntervals = rrIntervals;
}