Java Code Examples for android.bluetooth.BluetoothAdapter#getRemoteDevice()

The following examples show how to use android.bluetooth.BluetoothAdapter#getRemoteDevice() . 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: FitbitGatt.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Will retrieve a connection from the map if one exists using the bluetooth mac address
 * of the device, or will create one if it does not.
 *
 * @param context          The Android context
 * @param bluetoothAddress The bluetooth mac address
 * @return NULL if error creating creating connection, the connection if it does
 * @deprecated Using this method is discouraged as it will soon become private
 */
@Deprecated
public @Nullable
GattConnection getConnectionForBluetoothAddress(Context context, String bluetoothAddress) {
    BluetoothManager mgr = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
    if (mgr != null) {
        BluetoothAdapter adp = mgr.getAdapter();
        if (adp != null) {
            BluetoothDevice bluetoothDevice = adp.getRemoteDevice(bluetoothAddress);
            return getConnection(bluetoothDevice);
        } else {
            Timber.e("Couldn't fetch the connection because we couldn't initialize the adapter");
            return null;
        }
    } else {
        Timber.e("Couldn't fetch the connection because we couldn't initialize the manager");
        return null;
    }
}
 
Example 2
Source File: MkrSciBleManager.java    From science-journal with Apache License 2.0 6 votes vote down vote up
public static void subscribe(
    Context context, String address, String characteristic, Listener listener) {
  synchronized (gattHandlers) {
    GattHandler gattHandler = gattHandlers.get(address);
    if (gattHandler == null) {
      BluetoothManager manager =
          (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
      if (manager == null) {
        return;
      }
      BluetoothAdapter adapter = manager.getAdapter();
      BluetoothDevice device = adapter.getRemoteDevice(address);
      gattHandler = new GattHandler();
      gattHandlers.put(address, gattHandler);
      device.connectGatt(context, true /* autoConnect */, gattHandler);
    }
    gattHandler.subscribe(characteristic, listener);
  }
}
 
Example 3
Source File: BleProfileService.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    if (intent == null || !intent.hasExtra(EXTRA_DEVICE_ADDRESS))
        throw new UnsupportedOperationException("No device address at EXTRA_DEVICE_ADDRESS key");

    final Uri logUri = intent.getParcelableExtra(EXTRA_LOG_URI);
    logSession = Logger.openSession(getApplicationContext(), logUri);
    deviceName = intent.getStringExtra(EXTRA_DEVICE_NAME);

    Logger.i(logSession, "Service started");

    final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    final String deviceAddress = intent.getStringExtra(EXTRA_DEVICE_ADDRESS);
    bluetoothDevice = adapter.getRemoteDevice(deviceAddress);

    bleManager.setLogger(logSession);
    onServiceStarted();
    bleManager.connect(bluetoothDevice)
            .useAutoConnect(shouldAutoConnect())
            .retry(3, 100)
            .enqueue();
    return START_REDELIVER_INTENT;
}
 
Example 4
Source File: BleProfileService.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
	if (intent == null || !intent.hasExtra(EXTRA_DEVICE_ADDRESS))
		throw new UnsupportedOperationException("No device address at EXTRA_DEVICE_ADDRESS key");

	deviceName = intent.getStringExtra(EXTRA_DEVICE_NAME);

	final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
	final BluetoothAdapter adapter = bluetoothManager.getAdapter();
	final String deviceAddress = intent.getStringExtra(EXTRA_DEVICE_ADDRESS);
	bluetoothDevice = adapter.getRemoteDevice(deviceAddress);
	onServiceStarted();

	bleManager.connect(bluetoothDevice);
	return START_REDELIVER_INTENT;
}
 
Example 5
Source File: ScanFilterTest.java    From Android-Scanner-Compat-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Before public void setup() {
  byte[] scanRecord = new byte[] {
      0x02, 0x01, 0x1a, // advertising flags
      0x05, 0x02, 0x0b, 0x11, 0x0a, 0x11, // 16 bit service uuids
      0x04, 0x09, 0x50, 0x65, 0x64, // setName
      0x02, 0x0A, (byte) 0xec, // tx power level
      0x05, 0x16, 0x0b, 0x11, 0x50, 0x64, // service data
      0x05, (byte) 0xff, (byte) 0xe0, 0x00, 0x02, 0x15, // manufacturer specific data
      0x03, 0x50, 0x01, 0x02, // an unknown data type won't cause trouble
  };

  final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
  final BluetoothDevice device = adapter.getRemoteDevice(DEVICE_MAC);

  scanResult =
      new ScanResult(device, ScanRecord.parseFromBytes(scanRecord), -10, 1397545200000000L);
  filterBuilder = new ScanFilter.Builder();
}
 
Example 6
Source File: PuckActuator.java    From puck-central-android with Apache License 2.0 5 votes vote down vote up
@Override
void actuate(final JSONObject arguments) throws JSONException {
    String UUID = arguments.getString(ARGUMENT_UUID);
    int major = arguments.getInt(ARGUMENT_MAJOR);
    int minor = arguments.getInt(ARGUMENT_MINOR);
    Puck puck = mPuckManager.read(UUID, major, minor);

    BluetoothAdapter bluetoothAdapter = ((BluetoothManager) mContext.getSystemService
            (Context.BLUETOOTH_SERVICE)).getAdapter();
    BluetoothDevice device = bluetoothAdapter.getRemoteDevice(puck.getAddress());
    actuateOnPuck(device, arguments);
}
 
Example 7
Source File: TerminalFragment.java    From SimpleBluetoothLeTerminal with MIT License 5 votes vote down vote up
private void connect() {
    try {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
        status("connecting...");
        connected = Connected.Pending;
        SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), device);
        service.connect(socket);
    } catch (Exception e) {
        onSerialConnectError(e);
    }
}
 
Example 8
Source File: BluetoothThread.java    From android-arduino-bluetooth with MIT License 5 votes vote down vote up
/**
 * Connect to a remote Bluetooth socket, or throw an exception if it fails.
 */
private void connect() throws Exception {

    Log.i(TAG, "Attempting connection to " + address + "...");

    // Get this device's Bluetooth adapter
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if ((adapter == null) || (!adapter.isEnabled())){
        throw new Exception("Bluetooth adapter not found or not enabled!");
    }

    // Find the remote device
    BluetoothDevice remoteDevice = adapter.getRemoteDevice(address);

    // Create a socket with the remote device using this protocol
    socket = remoteDevice.createRfcommSocketToServiceRecord(uuid);

    // Make sure Bluetooth adapter is not in discovery mode
    adapter.cancelDiscovery();

    // Connect to the socket
    socket.connect();


    // Get input and output streams from the socket
    outStream = socket.getOutputStream();
    inStream = socket.getInputStream();

    Log.i(TAG, "Connected successfully to " + address + ".");
}
 
Example 9
Source File: BluetoothNeighbour.java    From Rumble with GNU General Public License v3.0 5 votes vote down vote up
public String getBluetoothDeviceName() {
    BluetoothAdapter adapter = BluetoothUtil.getBluetoothAdapter(RumbleApplication.getContext());
    if(adapter != null) {
        BluetoothDevice remote = adapter.getRemoteDevice(this.bluetoothMacAddress);
        if(remote != null)
            return remote.getName();
        else
            return bluetoothMacAddress;
    } else {
        return bluetoothMacAddress;
    }
}
 
Example 10
Source File: HRActivity.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void onStart() {
	super.onStart();

	final Intent intent = getIntent();
	if (!isDeviceConnected() && intent.hasExtra(FeaturesActivity.EXTRA_ADDRESS)) {
		final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(getIntent().getByteArrayExtra(FeaturesActivity.EXTRA_ADDRESS));
		onDeviceSelected(device, device.getName());

		intent.removeExtra(FeaturesActivity.EXTRA_APP);
		intent.removeExtra(FeaturesActivity.EXTRA_ADDRESS);
	}
}
 
Example 11
Source File: Bluetooth.java    From Arduino-Android-Bluetooth with GNU General Public License v2.0 5 votes vote down vote up
public void connectDevice(String deviceName) {
    // Get the device MAC address
    String address = null;
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    for(BluetoothDevice d: adapter.getBondedDevices()){
        if (d.getName().equals(deviceName)) address = d.getAddress();
    }

    try {
        BluetoothDevice device = adapter.getRemoteDevice(address); // Get the BluetoothDevice object
        this.connect(device); // Attempt to connect to the device
    } catch (Exception e){
        Log.e("Unable to connect to device address "+ address,e.getMessage());
    }
}
 
Example 12
Source File: BluetoothUtils.java    From Android-BluetoothKit with Apache License 2.0 5 votes vote down vote up
public static android.bluetooth.BluetoothDevice getRemoteDevice(String mac) {
    if (!TextUtils.isEmpty(mac)) {
        BluetoothAdapter adapter = getBluetoothAdapter();
        if (adapter != null) {
            return adapter.getRemoteDevice(mac);
        }
    }
    return null;
}
 
Example 13
Source File: BleConnectWorker.java    From Android-BluetoothKit with Apache License 2.0 5 votes vote down vote up
public BleConnectWorker(String mac, RuntimeChecker runtimeChecker) {
    BluetoothAdapter adapter = BluetoothUtils.getBluetoothAdapter();
    if (adapter != null) {
        mBluetoothDevice = adapter.getRemoteDevice(mac);
    } else {
        throw new IllegalStateException("ble adapter null");
    }

    mRuntimeChecker = runtimeChecker;
    mWorkerHandler = new Handler(Looper.myLooper(), this);
    mDeviceProfile = new HashMap<UUID, Map<UUID, BluetoothGattCharacteristic>>();
    mBluetoothGattResponse = ProxyUtils.getProxy(this, IBluetoothGattResponse.class, this);
}
 
Example 14
Source File: TerminalFragment.java    From SimpleBluetoothTerminal with MIT License 5 votes vote down vote up
private void connect() {
    try {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
        status("connecting...");
        connected = Connected.Pending;
        SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), device);
        service.connect(socket);
    } catch (Exception e) {
        onSerialConnectError(e);
    }
}
 
Example 15
Source File: BaseBleService.java    From bleYan with GNU General Public License v2.0 4 votes vote down vote up
public boolean directlyConnectDevice(String deviceMac, boolean autoConnect) {
	final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
	BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
	BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(deviceMac);
	return connectDevice(device, autoConnect);
}
 
Example 16
Source File: BluetoothServer.java    From BluetoothChatting with Apache License 2.0 4 votes vote down vote up
public Connect(String address, BluetoothAdapter bluetoothAdapter, Handler handler, BluetoothServer bluetoothServer) {
    mBluetoothAdapter = bluetoothAdapter;
    mBluetoothDevice = bluetoothAdapter.getRemoteDevice(address);
    this.mHandler = handler;
    mBluetoothServer = bluetoothServer;
}
 
Example 17
Source File: NukiRequestHandler.java    From trigger with GNU General Public License v2.0 4 votes vote down vote up
public void run() {
    if (bluetooth_in_use.get()) {
        Log.w(TAG, "Bluetooth busy => abort action");
        if (action != Action.fetch_state) {
            listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "Bluetooth device is busy.");
        }
        return;
    }

    if (!((Context) this.listener).getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        listener.onTaskResult(setup.getId(), ReplyCode.DISABLED, "Bluetooth Low Energy is not supported.");
        return;
    }

    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter == null || !adapter.isEnabled()) {
        this.listener.onTaskResult(setup.getId(), ReplyCode.DISABLED, "Bluetooth is disabled.");
        return;
    }

    if (setup.device_name.isEmpty()) {
        listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "No device name set.");
        return;
    }

    if (setup.user_name.isEmpty()) {
        listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "No user name set.");
        return;
    }

    String address = getAddress(adapter, setup.device_name);
    if (address == null) {
        listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "No Device found.");
        return;
    }

    BluetoothDevice device = adapter.getRemoteDevice(address);
    if (device == null) {
        this.listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "Device not found.");
        return;
    }

    if (Utils.isEmpty(setup.shared_key) && action == Action.fetch_state) {
        // ignore query for door state - not paired yet
        this.listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "");
        return;
    }

    if (!bluetooth_in_use.compareAndSet(false, true)) {
        // setting the variable failed
        return;
    }

    NukiCallback callback;
    if (Utils.isEmpty(setup.shared_key)) {
        // initiate paring
        callback = new NukiPairingCallback(setup.getId(), this.listener, setup);
        this.listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "Start Pairing.");
    } else switch (action) {
        case open_door:
            callback = new NukiLockActionCallback(setup.getId(), this.listener, setup, 0x01 /*unlock*/);
            break;
        case ring_door:
            this.listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "Bell not supported.");
            return;
        case close_door:
            callback = new NukiLockActionCallback(setup.getId(), this.listener, setup, 0x02 /*lock*/);
            break;
        default:
        case fetch_state:
            callback = new NukiReadLockStateCallback(setup.getId(), this.listener, setup);
            break;
    }

    BluetoothGatt gatt;

    if (Build.VERSION.SDK_INT >= 23) {
        gatt = device.connectGatt(this.context, false, callback, TRANSPORT_LE);
    } else {
        gatt = device.connectGatt(this.context, false, callback);
    }

    if (gatt == null) {
        // failed to start connection
        bluetooth_in_use.set(false);
    }
}
 
Example 18
Source File: BluetoothBackgroundService.java    From external-nfc-api with Apache License 2.0 4 votes vote down vote up
private boolean connectReader() {
    BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (bluetoothManager == null) {
        Log.w(TAG, "Unable to initialize BluetoothManager.");
        setConnectionState(BluetoothReader.STATE_DISCONNECTED);
        return false;
    }

    BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
    if (bluetoothAdapter == null) {
        Log.w(TAG, "Unable to obtain a BluetoothAdapter.");
        setConnectionState(BluetoothReader.STATE_DISCONNECTED);
        return false;
    }

    /*
     * Connect Device.
     */
    /* Clear old GATT connection. */
    if (bluetoothGatt != null) {
        Log.i(TAG, "Clear old GATT connection");
        bluetoothGatt.disconnect();
        bluetoothGatt.close();
        bluetoothGatt = null;
    }

    if (mDeviceAddress == null) {
        Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();

        if (mPairedDevices.size() > 0) {

            for (BluetoothDevice mDevice : mPairedDevices) {
                Log.i(TAG, "Connect bonded bluetooth device " + mDevice.getName() + " " + mDevice.getAddress());

                mDeviceAddress = mDevice.getAddress();
                mDeviceName = mDevice.getName();
            }
        } else {
            Log.i(TAG, "No connected bluetooth devices and no provided address.");

            return false;
        }
    } else {
        Log.i(TAG, "Connect bluetooth device " + mDeviceName + " " + mDeviceAddress);
    }

    /* Create a new connection. */
    final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(mDeviceAddress);

    if (device == null) {
        Log.w(TAG, "Device not found. Unable to connect.");
        return false;
    }

    /* Connect to GATT internal_invoker. */
    setConnectionState(BluetoothReader.STATE_CONNECTING);
    bluetoothGatt = device.connectGatt(this, false, acsGattCallback);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        bluetoothGatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);

        // https://stackoverflow.com/questions/53726759/xamarin-bluetooth-data-receive-delay
        // https://stackoverflow.com/questions/31742817/delay-between-writecharacteristic-and-callback-oncharacteristicwrite?noredirect=1&lq=1
        // https://punchthrough.com/maximizing-ble-throughput-part-2-use-larger-att-mtu-2/

        // When using larger ATT_MTU, the throughput is increased about 0-15% as we eliminate transferring ATT layer overhead bytes and replacing them with data.
        // Using ATT_MTU sizes that are multiples of 23 bytes or (Link Layer Data Field – L2CAP Header Size(4 bytes)) is ideal.

        bluetoothGatt.requestMtu(138);
    }
    return true;
}
 
Example 19
Source File: BluetoothIhealthHS3.java    From openScale with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void connect(String hwAddress) {
    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

    if (btAdapter == null) {
        setBluetoothStatus(BT_STATUS.NO_DEVICE_FOUND);
        return;
    }

    btDevice = btAdapter.getRemoteDevice(hwAddress);
    try {
        // Get a BluetoothSocket to connect with the given BluetoothDevice
        btSocket = btDevice.createRfcommSocketToServiceRecord(uuid);
    } catch (IOException e) {
        setBluetoothStatus(BT_STATUS.UNEXPECTED_ERROR, "Can't get a bluetooth socket");
        btDevice = null;
        return;
    }

    Thread socketThread = new Thread() {
        @Override
        public void run() {
            try {
                if (!btSocket.isConnected()) {
                    // Connect the device through the socket. This will block
                    // until it succeeds or throws an exception
                    btSocket.connect();

                    // Bluetooth connection was successful
                    setBluetoothStatus(BT_STATUS.CONNECTION_ESTABLISHED);

                    btConnectThread = new BluetoothConnectedThread();
                    btConnectThread.start();
                }
            } catch (IOException connectException) {
                // Unable to connect; close the socket and get out
                disconnect();
                setBluetoothStatus(BT_STATUS.NO_DEVICE_FOUND);
            }
        }
    };

    socketThread.start();
}
 
Example 20
Source File: FitbitGatt.java    From bitgatt with Mozilla Public License 2.0 3 votes vote down vote up
/**
 * Returns the BluetoothDevice Object for a remote Device that has the mac Address specified
 * <p> The mac Address should be a valid, such as "00:43:A8:23:10:F0"
 * Alphabetic characters must be uppercase to be valid.
 *
 * @param macAddress the mac address of the bluetooth device in question
 * @return The bluetooth device or null if not connected
 */
public BluetoothDevice getBluetoothDevice(String macAddress) {
    BluetoothAdapter adapter = getAdapter(appContext);
    if (adapter != null && BluetoothAdapter.checkBluetoothAddress(macAddress)) {
        return adapter.getRemoteDevice(macAddress);
    }
    return null;
}