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
@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 2
@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 3
@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 4
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 5
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 6
public BluetoothDevice getDevice()
{
	if( m_device.isNull() )
	{
		return m_device.getManager().newNativeDevice(BleDevice.NULL_MAC()).getNativeDevice();
	}
	else
	{
		return m_device_native.getNativeDevice();
	}
}
 
Example 7
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 8
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 9
Source Project: EFRConnect-android   Source File: BrowserActivity.java    License: Apache License 2.0 5 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 10
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 11
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 12
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 13
private void a(BluetoothDevice bluetoothdevice)
{
    o = bluetoothdevice;
    Utils.connect(bluetoothdevice, false);
    h.sendEmptyMessage(4097);
    h.sendEmptyMessageDelayed(4115, 60000L);
    UmengAnalytics.startEvent(l, "StartUpConnectBracelet");
}
 
Example 14
@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 15
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 16
@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 17
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 18
@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 19
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 20
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 21
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 22
@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;
}
 
Example 23
@Override
public void onContinuousGlucoseRateOfDecreaseAlertReceived(@NonNull final BluetoothDevice device, final float alertLevel, final boolean secured) {
	this.operationCompleted = true;
	this.requestCode = CGM_OP_CODE_SET_RATE_OF_DECREASE_ALERT_LEVEL;
	this.alertLevel = alertLevel;
	this.secured = secured;
	this.crcValid = secured;
}
 
Example 24
@Test
public void onInvalidDataReceived() {
	final ProfileReadResponse response = new MeasurementIntervalDataCallback() {
		@Override
		public void onMeasurementIntervalReceived(@NonNull final BluetoothDevice device, final int interval) {
			called = true;
		}
	};

	called = false;
	final Data data = new Data(new byte[] { 60 });
	response.onDataReceived(null, data);
	assertFalse(called);
	assertFalse(response.isValid());
}
 
Example 25
Source Project: ClassicBluetooth   Source File: CbtManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 设备连接
 *
 * @param callBack
 */
public void connectDevice(BluetoothDevice device, ConnectDeviceCallback callBack) {
    mConnCallBack = callBack;
    if (mBluetoothAdapter != null) {
        //配对蓝牙
        CbtClientService.getInstance().init(mBluetoothAdapter, device, callBack);
    }
}
 
Example 26
@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 27
Source Project: ELM327   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void scanAroundDevices()
{
    displayLog("Try to scan around devices...");

    if (mReceiver == null)
    {
        // Register the BroadcastReceiver
        mReceiver = new DeviceBroadcastReceiver();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);
    }

    // Start scanning
    mBluetoothAdapter.startDiscovery();
}
 
Example 28
Source Project: Makeblock-App-For-Android   Source File: Bluetooth.java    License: MIT License 5 votes vote down vote up
public List<String> getPairedList(){
       List<String> data = new ArrayList<String>();
       Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices();
       prDevices.clear();
	if (pairedDevices.size() > 0) {
           for (BluetoothDevice device : pairedDevices) {
               prDevices.add(device);
           }
       }
       for(BluetoothDevice dev : prDevices){
       	String s = dev.getName();
       	s=s+" "+dev.getAddress();
       	if(connDev!=null && connDev.equals(dev)){
       		s="-> "+s;
       	}
       	data.add(s);
       }
       return data;
}
 
Example 29
Source Project: Android-BLE-Terminal   Source File: BLeSerialPortService.java    License: MIT License 5 votes vote down vote up
private void notifyOnDeviceFound(BluetoothDevice device) {
    for (Callback cb : callbacks.keySet()) {
        if (cb != null) {
            cb.onDeviceFound(device);
        }
    }
}
 
Example 30
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    final BluetoothDevice device = leDeviceListAdapter.getDevice(position);
    if (device == null)
        return;

    final Intent intent = new Intent(this, DeviceServicesActivity.class);
    intent.putExtra(DeviceServicesActivity.EXTRAS_DEVICE_NAME, device.getName());
    intent.putExtra(DeviceServicesActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
    startActivity(intent);
}