File: bluetooth_adapter_android.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (581 lines) | stat: -rw-r--r-- 22,410 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "device/bluetooth/bluetooth_adapter_android.h"

#include <memory>
#include <string>

#include "base/android/jni_android.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/notimplemented.h"
#include "base/task/single_thread_task_runner.h"
#include "device/base/features.h"
#include "device/bluetooth/android/wrappers.h"
#include "device/bluetooth/bluetooth_advertisement.h"
#include "device/bluetooth/bluetooth_common.h"
#include "device/bluetooth/bluetooth_device.h"
#include "device/bluetooth/bluetooth_device_android.h"
#include "device/bluetooth/bluetooth_discovery_session_outcome.h"
#include "device/bluetooth/bluetooth_socket_thread.h"
// Must come after all headers that specialize FromJniType() / ToJniType().
#include "device/bluetooth/jni_headers/ChromeBluetoothAdapter_jni.h"
#include "device/bluetooth/jni_headers/ChromeBluetoothScanFilterBuilder_jni.h"
#include "device/bluetooth/jni_headers/ChromeBluetoothScanFilterList_jni.h"

using base::android::AppendJavaStringArrayToStringVector;
using base::android::AttachCurrentThread;
using base::android::ConvertJavaStringToUTF8;
using base::android::JavaArrayOfByteArrayToBytesVector;
using base::android::JavaByteArrayToByteVector;
using base::android::JavaIntArrayToIntVector;
using base::android::JavaParamRef;
using base::android::JavaRef;

namespace {
// The poll interval in ms when there is no active discovery. This
// matches the max allowed advertisting interval for connectable
// devices.
enum { kPassivePollInterval = 11000 };
// The poll interval in ms when there is an active discovery.
enum { kActivePollInterval = 1000 };
// The delay in ms to wait before purging devices when a scan starts.
enum { kPurgeDelay = 500 };
}  // namespace

namespace device {

// static
scoped_refptr<BluetoothAdapter> BluetoothAdapter::CreateAdapter() {
  return BluetoothAdapterAndroid::Create(
      BluetoothAdapterWrapper_CreateWithDefaultAdapter(
          base::FeatureList::IsEnabled(features::kBluetoothRfcommAndroid)));
}

// static
scoped_refptr<BluetoothAdapterAndroid> BluetoothAdapterAndroid::Create(
    const JavaRef<jobject>&
        bluetooth_adapter_wrapper) {  // Java Type: BluetoothAdapterWrapper
  auto adapter = base::WrapRefCounted(new BluetoothAdapterAndroid());

  adapter->j_adapter_.Reset(Java_ChromeBluetoothAdapter_create(
      AttachCurrentThread(), reinterpret_cast<intptr_t>(adapter.get()),
      bluetooth_adapter_wrapper));

  adapter->ui_task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault();
  adapter->socket_thread_ = BluetoothSocketThread::Get();

  return adapter;
}

void BluetoothAdapterAndroid::Initialize(base::OnceClosure callback) {
  std::move(callback).Run();
}

std::string BluetoothAdapterAndroid::GetAddress() const {
  return ConvertJavaStringToUTF8(Java_ChromeBluetoothAdapter_getAddress(
      AttachCurrentThread(), j_adapter_));
}

std::string BluetoothAdapterAndroid::GetName() const {
  return ConvertJavaStringToUTF8(
      Java_ChromeBluetoothAdapter_getName(AttachCurrentThread(), j_adapter_));
}

void BluetoothAdapterAndroid::SetName(const std::string& name,
                                      base::OnceClosure callback,
                                      ErrorCallback error_callback) {
  NOTIMPLEMENTED();
}

bool BluetoothAdapterAndroid::IsInitialized() const {
  return true;
}

bool BluetoothAdapterAndroid::IsPresent() const {
  return Java_ChromeBluetoothAdapter_isPresent(AttachCurrentThread(),
                                               j_adapter_);
}

BluetoothAdapter::PermissionStatus
BluetoothAdapterAndroid::GetOsPermissionStatus() const {
  return static_cast<BluetoothAdapter::PermissionStatus>(
      Java_ChromeBluetoothAdapter_getOsPermissionStatus(AttachCurrentThread(),
                                                        j_adapter_));
}

bool BluetoothAdapterAndroid::IsPowered() const {
  return Java_ChromeBluetoothAdapter_isPowered(AttachCurrentThread(),
                                               j_adapter_);
}

bool BluetoothAdapterAndroid::IsDiscoverable() const {
  return Java_ChromeBluetoothAdapter_isDiscoverable(AttachCurrentThread(),
                                                    j_adapter_);
}

void BluetoothAdapterAndroid::SetDiscoverable(bool discoverable,
                                              base::OnceClosure callback,
                                              ErrorCallback error_callback) {
  NOTIMPLEMENTED();
}

bool BluetoothAdapterAndroid::IsDiscovering() const {
  return Java_ChromeBluetoothAdapter_isDiscovering(AttachCurrentThread(),
                                                   j_adapter_);
}

BluetoothAdapter::ConstDeviceList BluetoothAdapterAndroid::GetDevices() const {
  PopulatePairedDevices();
  return BluetoothAdapter::GetDevices();
}

void BluetoothAdapterAndroid::PopulatePairedDevices() const {
  if (!base::FeatureList::IsEnabled(features::kBluetoothRfcommAndroid)) {
    return;
  }

  Java_ChromeBluetoothAdapter_populatePairedDevices(AttachCurrentThread(),
                                                    j_adapter_);
}

BluetoothAdapter::UUIDList BluetoothAdapterAndroid::GetUUIDs() const {
  NOTIMPLEMENTED();
  return UUIDList();
}

void BluetoothAdapterAndroid::CreateRfcommService(
    const BluetoothUUID& uuid,
    const ServiceOptions& options,
    CreateServiceCallback callback,
    CreateServiceErrorCallback error_callback) {
  NOTIMPLEMENTED();
  std::move(error_callback).Run("Not Implemented");
}

void BluetoothAdapterAndroid::CreateL2capService(
    const BluetoothUUID& uuid,
    const ServiceOptions& options,
    CreateServiceCallback callback,
    CreateServiceErrorCallback error_callback) {
  NOTIMPLEMENTED();
  std::move(error_callback).Run("Not Implemented");
}

void BluetoothAdapterAndroid::RegisterAdvertisement(
    std::unique_ptr<BluetoothAdvertisement::Data> advertisement_data,
    CreateAdvertisementCallback callback,
    AdvertisementErrorCallback error_callback) {
  std::move(error_callback)
      .Run(BluetoothAdvertisement::ERROR_UNSUPPORTED_PLATFORM);
}

BluetoothLocalGattService* BluetoothAdapterAndroid::GetGattService(
    const std::string& identifier) const {
  return nullptr;
}

void BluetoothAdapterAndroid::OnAdapterStateChanged(
    JNIEnv* env,
    const JavaParamRef<jobject>& caller,
    const bool powered) {
  RunPendingPowerCallbacks();
  NotifyAdapterPoweredChanged(powered);
  if (!powered) {
    UpdateDeviceConnectStatesOnAdapterOff();
  }
}

void BluetoothAdapterAndroid::UpdateDeviceConnectStatesOnAdapterOff() {
  for (auto& device : devices_) {
    BluetoothDeviceAndroid* device_android =
        static_cast<BluetoothDeviceAndroid*>(device.second.get());
    if (device_android->is_acl_connected()) {
      device_android->UpdateAclConnectState(BLUETOOTH_TRANSPORT_DUAL,
                                            /*connected=*/false);
      NotifyDeviceChanged(device_android);
    }
  }
}

void BluetoothAdapterAndroid::OnScanFailed(
    JNIEnv* env,
    const JavaParamRef<jobject>& caller) {
  MarkDiscoverySessionsAsInactive();
}

void BluetoothAdapterAndroid::CreateOrUpdateDeviceOnScan(
    JNIEnv* env,
    const JavaParamRef<jobject>& caller,
    const JavaParamRef<jstring>& address,
    const JavaParamRef<jobject>&
        bluetooth_device_wrapper,  // Java Type: bluetoothDeviceWrapper
    const JavaParamRef<jstring>& local_name,
    int32_t rssi,
    const JavaParamRef<jobjectArray>& advertised_uuids,  // Java Type: String[]
    int32_t tx_power,
    const JavaParamRef<jobjectArray>& service_data_keys,  // Java Type: String[]
    const JavaParamRef<jobjectArray>& service_data_values,  // Java Type: byte[]
    const JavaParamRef<jintArray>& manufacturer_data_keys,  // Java Type: int[]
    const JavaParamRef<jobjectArray>&
        manufacturer_data_values,  // Java Type: byte[]
    int32_t advertisement_flags) {
  std::string device_address = ConvertJavaStringToUTF8(env, address);
  auto iter = devices_.find(device_address);

  bool is_new_device = false;
  BluetoothDeviceAndroid* device_android;

  if (iter == devices_.end()) {
    // New device.
    is_new_device = true;
    device_android = CreateDevice(device_address, bluetooth_device_wrapper);
  } else {
    // Existing device.
    device_android = static_cast<BluetoothDeviceAndroid*>(iter->second.get());
  }
  DCHECK(device_android);

  std::vector<std::string> advertised_uuids_strings;
  AppendJavaStringArrayToStringVector(env, advertised_uuids,
                                      &advertised_uuids_strings);
  BluetoothDevice::UUIDList advertised_bluetooth_uuids;
  for (std::string& uuid : advertised_uuids_strings) {
    advertised_bluetooth_uuids.push_back(BluetoothUUID(std::move(uuid)));
  }

  std::vector<std::string> service_data_keys_vector;
  std::vector<std::vector<uint8_t>> service_data_values_vector;
  AppendJavaStringArrayToStringVector(env, service_data_keys,
                                      &service_data_keys_vector);
  JavaArrayOfByteArrayToBytesVector(env, service_data_values,
                                    &service_data_values_vector);
  BluetoothDeviceAndroid::ServiceDataMap service_data_map;
  for (size_t i = 0; i < service_data_keys_vector.size(); i++) {
    service_data_map.insert({BluetoothUUID(service_data_keys_vector[i]),
                             service_data_values_vector[i]});
  }

  std::vector<jint> manufacturer_data_keys_vector;
  std::vector<std::vector<uint8_t>> manufacturer_data_values_vector;
  JavaIntArrayToIntVector(env, manufacturer_data_keys,
                          &manufacturer_data_keys_vector);
  JavaArrayOfByteArrayToBytesVector(env, manufacturer_data_values,
                                    &manufacturer_data_values_vector);
  BluetoothDeviceAndroid::ManufacturerDataMap manufacturer_data_map;
  for (size_t i = 0; i < manufacturer_data_keys_vector.size(); i++) {
    manufacturer_data_map.insert(
        {static_cast<uint16_t>(manufacturer_data_keys_vector[i]),
         manufacturer_data_values_vector[i]});
  }

  int8_t clamped_tx_power = BluetoothDevice::ClampPower(tx_power);

  device_android->UpdateAdvertisementData(
      BluetoothDevice::ClampPower(rssi),
      // Android uses -1 to indicate no advertising flags.
      // https://developer.android.com/reference/android/bluetooth/le/ScanRecord.html#getAdvertiseFlags()
      advertisement_flags == -1 ? std::nullopt
                                : std::make_optional(advertisement_flags),
      advertised_bluetooth_uuids,
      // Android uses INT32_MIN to indicate no Advertised Tx Power.
      // https://developer.android.com/reference/android/bluetooth/le/ScanRecord.html#getTxPowerLevel()
      tx_power == INT32_MIN ? std::nullopt
                            : std::make_optional(clamped_tx_power),
      service_data_map, manufacturer_data_map);

  for (auto& observer : observers_) {
    std::optional<std::string> device_name_opt = device_android->GetName();
    std::optional<std::string> advertisement_name_opt;
    if (local_name)
      advertisement_name_opt = ConvertJavaStringToUTF8(env, local_name);

    observer.DeviceAdvertisementReceived(
        device_android->GetAddress(), device_name_opt, advertisement_name_opt,
        BluetoothDevice::ClampPower(rssi),
        // Android uses INT32_MIN to indicate no Advertised Tx Power.
        // https://developer.android.com/reference/android/bluetooth/le/ScanRecord.html#getTxPowerLevel()
        tx_power == INT32_MIN ? std::nullopt
                              : std::make_optional(clamped_tx_power),
        std::nullopt, /* TODO(crbug.com/41240161) Implement appearance */
        advertised_bluetooth_uuids, service_data_map, manufacturer_data_map);
  }

  if (is_new_device) {
    for (auto& observer : observers_)
      observer.DeviceAdded(this, device_android);
  } else {
    for (auto& observer : observers_)
      observer.DeviceChanged(this, device_android);
  }
}

void BluetoothAdapterAndroid::PopulateOrUpdatePairedDevice(
    JNIEnv* env,
    const base::android::JavaParamRef<jobject>& caller,
    const base::android::JavaParamRef<jstring>& address,
    const base::android::JavaParamRef<jobject>&
        bluetooth_device_wrapper,  // Java Type: bluetoothDeviceWrapper
    bool from_broadcast_receiver) {
  std::string device_address = ConvertJavaStringToUTF8(env, address);
  auto iter = devices_.find(device_address);

  bool is_new_device = iter == devices_.end();
  if (!is_new_device) {
    // If an event doesn't come from the broadcast receiver, then we're
    // pushing already paired devices in GetDevices() from Java code to native
    // code. There is no need to notify observers because the device paired
    // state doesn't change.
    if (from_broadcast_receiver) {
      NotifyDeviceChanged(iter->second.get());
    }
    return;
  }

  BluetoothDeviceAndroid* device =
      CreateDevice(device_address, bluetooth_device_wrapper);

  // We don't notify observers for populated paired devices unless it's from
  // bonded state broadcast receiver. See crbug.com/387371131 for more details.
  if (!from_broadcast_receiver) {
    return;
  }

  for (auto& observer : observers_) {
    observer.DeviceAdded(this, device);
  }
}

void BluetoothAdapterAndroid::OnDeviceUnpaired(
    JNIEnv* env,
    const base::android::JavaParamRef<jobject>& caller,
    const base::android::JavaParamRef<jstring>& address) {
  std::string device_address = ConvertJavaStringToUTF8(env, address);
  auto iter = devices_.find(device_address);
  if (iter == devices_.end()) {
    return;
  }

  base::TimeDelta duration_before_expiry = iter->second->GetLastUpdateTime() +
                                           BluetoothAdapter::timeoutSec -
                                           base::Time::NowFromSystemTime();
  if (duration_before_expiry.is_negative() ||
      duration_before_expiry.is_zero()) {
    RemoveTimedOutDevices();
    return;
  }

  ui_task_runner_->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&BluetoothAdapterAndroid::RemoveTimedOutDevices,
                     weak_ptr_factory_.GetWeakPtr()),
      duration_before_expiry);
}

void BluetoothAdapterAndroid::UpdateDeviceAclConnectState(
    JNIEnv* env,
    const base::android::JavaParamRef<jobject>& caller,
    const base::android::JavaParamRef<jstring>& address,
    const base::android::JavaParamRef<jobject>&
        bluetooth_device_wrapper,  // Java Type: BluetoothDeviceWrapper
    uint8_t transport,
    bool connected) {
  std::string device_address = ConvertJavaStringToUTF8(env, address);

  auto iter = devices_.find(device_address);
  bool is_new_device = iter == devices_.end();
  if (is_new_device && !connected) {
    return;
  }

  BluetoothDeviceAndroid* device;
  if (is_new_device) {
    device = CreateDevice(device_address, bluetooth_device_wrapper);
  } else {
    device = static_cast<BluetoothDeviceAndroid*>(iter->second.get());
  }

  bool was_connected = device->IsConnected();
  device->UpdateAclConnectState(transport, connected);

  if (is_new_device) {
    for (auto& observer : observers_) {
      observer.DeviceAdded(this, device);
    }
    return;
  }

  // Not a new device.
  bool is_connected = device->IsConnected();
  if (was_connected != is_connected) {
    NotifyDeviceChanged(device);
  }
}

BluetoothDeviceAndroid* BluetoothAdapterAndroid::CreateDevice(
    const std::string& device_address,
    const base::android::JavaParamRef<jobject>&
        bluetooth_device_wrapper) {  // Java Type: BluetoothDeviceWrapper
  BluetoothDeviceAndroid* device;
  std::unique_ptr<BluetoothDeviceAndroid> device_owner =
      BluetoothDeviceAndroid::Create(this, bluetooth_device_wrapper,
                                     ui_task_runner_, socket_thread_);
  device = device_owner.get();
  devices_[device_address] = std::move(device_owner);
  return device;
}

BluetoothAdapterAndroid::BluetoothAdapterAndroid() {}

BluetoothAdapterAndroid::~BluetoothAdapterAndroid() {
  Java_ChromeBluetoothAdapter_onBluetoothAdapterAndroidDestruction(
      AttachCurrentThread(), j_adapter_);
}

void BluetoothAdapterAndroid::PurgeTimedOutDevices() {
  RemoveTimedOutDevices();
  if (IsDiscovering()) {
    ui_task_runner_->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&BluetoothAdapterAndroid::PurgeTimedOutDevices,
                       weak_ptr_factory_.GetWeakPtr()),
        base::Milliseconds(kActivePollInterval));
  } else {
    ui_task_runner_->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&BluetoothAdapterAndroid::RemoveTimedOutDevices,
                       weak_ptr_factory_.GetWeakPtr()),
        base::Milliseconds(kPassivePollInterval));
  }
}

base::WeakPtr<BluetoothAdapter> BluetoothAdapterAndroid::GetWeakPtr() {
  return weak_ptr_factory_.GetWeakPtr();
}

bool BluetoothAdapterAndroid::SetPoweredImpl(bool powered) {
  return Java_ChromeBluetoothAdapter_setPowered(AttachCurrentThread(),
                                                j_adapter_, powered);
}

void BluetoothAdapterAndroid::UpdateFilter(
    std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter,
    DiscoverySessionResultCallback callback) {
  // If there is only 1 discovery session then StartScan should be called and
  // not UpdateFilter.
  DCHECK_GT(NumDiscoverySessions(), 1);
  if (IsPowered()) {
    // TODO(jameshollyer): Actually update the filter in Android.
    std::move(callback).Run(/*is_error=*/false,
                            UMABluetoothDiscoverySessionOutcome::SUCCESS);
    return;
  } else {
    DVLOG(1) << "UpdateFilter: Fails: !isPowered";
    std::move(callback).Run(/*is_error=*/true,
                            UMABluetoothDiscoverySessionOutcome::UNKNOWN);
  }
}

base::android::ScopedJavaLocalRef<jobject>
BluetoothAdapterAndroid::CreateAndroidFilter(
    const BluetoothDiscoveryFilter* discovery_filter) {
  base::android::ScopedJavaLocalRef<jobject> android_filters =
      Java_ChromeBluetoothScanFilterList_create(AttachCurrentThread());
  const base::flat_set<device::BluetoothDiscoveryFilter::DeviceInfoFilter>*
      device_filters = discovery_filter->GetDeviceFilters();
  for (const auto& device_filter : *device_filters) {
    base::android::ScopedJavaLocalRef<jobject> filter_builder =
        Java_ChromeBluetoothScanFilterBuilder_create(AttachCurrentThread());
    if (!device_filter.uuids.empty()) {
      // Set the service UUID to the first UUID in the list because Android does
      // not support filtering for multiple UUIDs. This will return a superset
      // of the devices that advertise all UUIDs in the list and it will be
      // filtered internally when returned.
      Java_ChromeBluetoothScanFilterBuilder_setServiceUuid(
          AttachCurrentThread(), filter_builder,
          base::android::ConvertUTF8ToJavaString(
              AttachCurrentThread(), device_filter.uuids.begin()->value()));
    }
    if (!device_filter.name.empty()) {
      Java_ChromeBluetoothScanFilterBuilder_setDeviceName(
          AttachCurrentThread(), filter_builder,
          base::android::ConvertUTF8ToJavaString(AttachCurrentThread(),
                                                 device_filter.name));
    }
    base::android::ScopedJavaLocalRef<jobject> scan_filter =
        Java_ChromeBluetoothScanFilterBuilder_build(AttachCurrentThread(),
                                                    filter_builder);
    Java_ChromeBluetoothScanFilterList_addFilter(AttachCurrentThread(),
                                                 android_filters, scan_filter);
  }

  return Java_ChromeBluetoothScanFilterList_getList(AttachCurrentThread(),
                                                    android_filters);
}

void BluetoothAdapterAndroid::StartScanWithFilter(
    std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter,
    DiscoverySessionResultCallback callback) {
  // This function should only be called if this is the first discovery session.
  // Otherwise we should have called updateFilter.
  DCHECK_EQ(NumDiscoverySessions(), 1);

  bool session_added = false;
  if (IsPowered()) {
    auto android_scan_filter = CreateAndroidFilter(discovery_filter.get());
    if (Java_ChromeBluetoothAdapter_startScan(AttachCurrentThread(), j_adapter_,
                                              android_scan_filter)) {
      session_added = true;

      // Using a delayed task in order to give the adapter some time
      // to settle before purging devices.
      ui_task_runner_->PostDelayedTask(
          FROM_HERE,
          base::BindOnce(&BluetoothAdapterAndroid::PurgeTimedOutDevices,
                         weak_ptr_factory_.GetWeakPtr()),
          base::Milliseconds(kPurgeDelay));
    }
  } else {
    DVLOG(1) << "StartScanWithFilter: Fails: !isPowered";
  }

  if (session_added) {
    DVLOG(1) << "StartScanWithFilter: Now " << unsigned(NumDiscoverySessions())
             << " sessions.";
    std::move(callback).Run(/*is_error=*/false,
                            UMABluetoothDiscoverySessionOutcome::SUCCESS);
  } else {
    // TODO(scheib): Eventually wire the SCAN_FAILED result through to here.
    std::move(callback).Run(/*is_error=*/true,
                            UMABluetoothDiscoverySessionOutcome::UNKNOWN);
  }
}

void BluetoothAdapterAndroid::StopScan(
    DiscoverySessionResultCallback callback) {
  DCHECK(NumDiscoverySessions() == 0);

  DVLOG(1) << "Stopping scan.";
  if (Java_ChromeBluetoothAdapter_stopScan(AttachCurrentThread(), j_adapter_)) {
    std::move(callback).Run(/*is_error=*/false,
                            UMABluetoothDiscoverySessionOutcome::SUCCESS);
  } else {
    // TODO(scheib): Eventually wire the SCAN_FAILED result through to here.
    std::move(callback).Run(/*is_error=*/true,
                            UMABluetoothDiscoverySessionOutcome::UNKNOWN);
  }
  for (const auto& device_id_object_pair : devices_)
    device_id_object_pair.second->ClearAdvertisementData();
}

void BluetoothAdapterAndroid::RemovePairingDelegateInternal(
    device::BluetoothDevice::PairingDelegate* pairing_delegate) {}

}  // namespace device