Идея в том, что в приложении вы сканируете список устройств BLE. Вы выбираете один (или несколько) из них, и как только любой из них подключается или отключается от телефона, приложение может быть запущено и отправить уведомление о том, что ваше устройство подключилось/отключилось от (устройство BLE) (независимо от вашего приложение работает в фоновом или активном режиме или завершается)
Кажется, это возможно на Android, но после нескольких дней исследований я не нашел никакой документации, которая могла бы помочь.
Есть идеи?
ОБНОВЛЕНИЕ:
Ниже приведен мой код.
Я несколько раз пытался подключить/отключить свои AirPods. Когда приложение работает на переднем плане, я вижу, что каждый раз вызываются как события подключения, так и отключения. Но я вижу, что отключенные события вызываются только в том случае, если приложение работает в фоновом режиме.
У меня также включены «Использует аксессуары Bluetooth LE» и «Действует как аксессуар Bluetooth LE». .
public class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeripheralDelegate {
var myCentral: CBCentralManager!
@Published var isSwitchedOn = false
@Published var peripherals: [CBPeripheral] = []
@Published var connectingCBperipheral: CBPeripheral?
@Published var connectedCBperipheral: CBPeripheral?
func sendNotification(title: String, body: String) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.default
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error adding notification: \(error)")
}
}
}
override public init() {
super.init()
myCentral = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey: "myCentralManagerIdentifier"])
}
public func startScanning() {
myCentral.scanForPeripherals(withServices: nil)
}
public func stopScanning() {
myCentral.stopScan()
}
public func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
if let restoredPeripherals = dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral] {
for peripheral in restoredPeripherals {
guard peripheral.name == connectedCBperipheral?.name else {
return
}
sendNotification(title: "Restored", body: "Restored connection to \(peripheral.name ?? "device")")
// You can also discover services, etc.
}
}
}
public func centralManagerDidUpdateState(_ central: CBCentralManager) {
isSwitchedOn = central.state == .poweredOn
if isSwitchedOn {
startScanning()
} else {
stopScanning()
}
}
public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
guard peripheral.name != nil else { return }
DispatchQueue.main.async {
if !self.peripherals.contains(where: { $0.identifier == peripheral.identifier }) {
self.peripherals.append(peripheral)
}
if let connectingCBperipheral = self.connectingCBperipheral, self.connectedCBperipheral == nil {
self.connect(to: connectingCBperipheral)
}
}
}
public func selectPheripheralToObserveConnection(_ item: CBPeripheral) {
connectingCBperipheral = item
}
func disconect() {
guard let item = connectedCBperipheral else { return }
myCentral.cancelPeripheralConnection(item)
}
func connect(to peripheral: CBPeripheral) {
guard let cbperipheral = myCentral.retrievePeripherals(withIdentifiers: [peripheral.identifier]).first,
cbperipheral.state != .connected else { return }
peripheral.delegate = self
myCentral.connect(cbperipheral, options: [:])
}
public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
guard peripheral != connectedCBperipheral else { return }
print("Connected to \(peripheral.name ?? "Unknown") ", peripheral.identifier.uuidString)
connectedCBperipheral = peripheral
peripheral.delegate = self
sendNotification(title: "Connected", body: "Connected to \(peripheral.name ?? "device")")
}
public func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: (any Error)?) {
print("Did disconnect to \(peripheral)", error?.localizedDescription ?? "")
connectedCBperipheral = nil
sendNotification(title: "Disconnected", body: "Disconnected from \(peripheral.name ?? "device")")
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... -the-phone
IOS – Как получить уведомление, когда устройство BLE подключено к телефону? ⇐ IOS
Программируем под IOS
1729115955
Anonymous
Идея в том, что в приложении вы сканируете список устройств BLE. Вы выбираете один (или несколько) из них, и как только любой из них подключается или отключается от телефона, приложение может быть запущено и отправить уведомление о том, что ваше устройство подключилось/отключилось от (устройство BLE) (независимо от вашего приложение работает в фоновом или активном режиме или завершается)
Кажется, это возможно на Android, но после нескольких дней исследований я не нашел никакой документации, которая могла бы помочь.
Есть идеи?
[b]ОБНОВЛЕНИЕ:[/b]
Ниже приведен мой код.
Я несколько раз пытался подключить/отключить свои AirPods. Когда приложение работает на [b]переднем плане[/b], я вижу, что каждый раз вызываются как события подключения, так и отключения. Но я вижу, что отключенные события вызываются только в том случае, если приложение работает в фоновом режиме.
У меня также включены «Использует аксессуары Bluetooth LE» и «Действует как аксессуар Bluetooth LE». .
public class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeripheralDelegate {
var myCentral: CBCentralManager!
@Published var isSwitchedOn = false
@Published var peripherals: [CBPeripheral] = []
@Published var connectingCBperipheral: CBPeripheral?
@Published var connectedCBperipheral: CBPeripheral?
func sendNotification(title: String, body: String) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.default
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error adding notification: \(error)")
}
}
}
override public init() {
super.init()
myCentral = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey: "myCentralManagerIdentifier"])
}
public func startScanning() {
myCentral.scanForPeripherals(withServices: nil)
}
public func stopScanning() {
myCentral.stopScan()
}
public func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
if let restoredPeripherals = dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral] {
for peripheral in restoredPeripherals {
guard peripheral.name == connectedCBperipheral?.name else {
return
}
sendNotification(title: "Restored", body: "Restored connection to \(peripheral.name ?? "device")")
// You can also discover services, etc.
}
}
}
public func centralManagerDidUpdateState(_ central: CBCentralManager) {
isSwitchedOn = central.state == .poweredOn
if isSwitchedOn {
startScanning()
} else {
stopScanning()
}
}
public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
guard peripheral.name != nil else { return }
DispatchQueue.main.async {
if !self.peripherals.contains(where: { $0.identifier == peripheral.identifier }) {
self.peripherals.append(peripheral)
}
if let connectingCBperipheral = self.connectingCBperipheral, self.connectedCBperipheral == nil {
self.connect(to: connectingCBperipheral)
}
}
}
public func selectPheripheralToObserveConnection(_ item: CBPeripheral) {
connectingCBperipheral = item
}
func disconect() {
guard let item = connectedCBperipheral else { return }
myCentral.cancelPeripheralConnection(item)
}
func connect(to peripheral: CBPeripheral) {
guard let cbperipheral = myCentral.retrievePeripherals(withIdentifiers: [peripheral.identifier]).first,
cbperipheral.state != .connected else { return }
peripheral.delegate = self
myCentral.connect(cbperipheral, options: [:])
}
public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
guard peripheral != connectedCBperipheral else { return }
print("Connected to \(peripheral.name ?? "Unknown") ", peripheral.identifier.uuidString)
connectedCBperipheral = peripheral
peripheral.delegate = self
sendNotification(title: "Connected", body: "Connected to \(peripheral.name ?? "device")")
}
public func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: (any Error)?) {
print("Did disconnect to \(peripheral)", error?.localizedDescription ?? "")
connectedCBperipheral = nil
sendNotification(title: "Disconnected", body: "Disconnected from \(peripheral.name ?? "device")")
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79070195/ios-how-to-be-notified-when-a-ble-device-is-connected-to-the-phone[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия