Skip to content

Commit 9aa4e85

Browse files
committed
Fix AndroidCentral.scan()
1 parent 3637702 commit 9aa4e85

1 file changed

Lines changed: 22 additions & 2 deletions

File tree

Sources/AndroidBluetooth/AndroidCentral.swift

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import JavaUtil
1818
import JavaLangUtil
1919
import AndroidOS
2020
import AndroidContent
21+
import AndroidManifest
2122

2223
/// Android GATT Central
2324
public final class AndroidCentral: CentralManager {
@@ -42,6 +43,13 @@ public final class AndroidCentral: CentralManager {
4243

4344
public var isEnabled: Bool {
4445
get async {
46+
do {
47+
try checkPermission(Permission(rawValue: JavaClass<Manifest.Permission>().BLUETOOTH_SCAN))
48+
}
49+
catch {
50+
return false
51+
}
52+
// Make sure hardware is on
4553
return hostController.isEnabled()
4654
&& hostController.getBluetoothLeScanner() != nil
4755
}
@@ -77,6 +85,10 @@ public final class AndroidCentral: CentralManager {
7785
guard let scanner = hostController.getBluetoothLeScanner()
7886
else { throw AndroidCentralError.bluetoothDisabled }
7987

88+
// check permission
89+
let permission = try Permission(rawValue: JavaClass<Manifest.Permission>().BLUETOOTH_SCAN)
90+
try checkPermission(permission)
91+
8092
return .init(onTermination: {
8193
Task {
8294
await self.stopScan()
@@ -137,13 +149,13 @@ public final class AndroidCentral: CentralManager {
137149
let sdkInt = try! JavaClass<AndroidOS.Build.VERSION>().SDK_INT
138150
let lollipopMr1 = try! JavaClass<AndroidOS.Build.VERSION_CODES>().LOLLIPOP_MR1
139151
if sdkInt <= lollipopMr1 {
140-
gatt = scanDevice.scanResult.getDevice().connectGatt(
152+
gatt = try! scanDevice.scanResult.getDevice().connectGatt(
141153
context: self.context,
142154
autoConnect: autoConnect,
143155
callback: callback
144156
)
145157
} else {
146-
gatt = scanDevice.scanResult.getDevice().connectGatt(
158+
gatt = try! scanDevice.scanResult.getDevice().connectGatt(
147159
context: self.context,
148160
autoConnect: autoConnect,
149161
callback: callback,
@@ -522,6 +534,14 @@ public final class AndroidCentral: CentralManager {
522534

523535
// MARK: - Private Methods
524536

537+
private func checkPermission(_ permission: AndroidManifest.Permission) throws {
538+
let granted = try JavaClass<PackageManager>().PERMISSION_GRANTED
539+
let status = context.checkSelfPermission(permission.rawValue)
540+
guard status == granted else {
541+
throw AndroidCentralError.bluetoothDisabled
542+
}
543+
}
544+
525545
private func stopScan() async {
526546

527547
guard hostController.isEnabled()

0 commit comments

Comments
 (0)