0

当我的 iOS 应用程序打开时,它会显示一个本地蓝牙设备列表,然后您单击一个。如果蓝牙关闭,则会出现系统警报,要求您将其打开(带有一个按钮可以转到“设置”,另一个按钮可以单击“确定”);如果您打开设置,它不会再次扫描,您必须

如何注册一种在蓝牙打开时运行方法的通知?

我看到了一些关于“BluetoothAvailabilityChangedNotification”的东西,但是当蓝牙打开/关闭时似乎没有被调用。

这是我尝试过的代码:

[[NSNotificationCenter defaultCenter]
 addObserver:self
 selector:@selector(bluetoothAvailabilityChanged:)
 name:@"BluetoothAvailabilityChangedNotification"
 object:nil];

...

-(void) bluetoothAvailabilityChanged: (NSNotification*) notification {
NSLog(@"Bluetooth changed %@",notification.description);
}
4

3 回答 3

7

要获得蓝牙状态更改指示,您可以尝试使用 CoreBluetooth lib
1. 将 CoreBluetooth.framework 链接到您的项目
2.#import <CoreBluetooth/CoreBluetooth.h>在您的 .h 文件中
3. 实施CBCentralManagerDelegate
4. 以 self 作为委托初始化管理器
CBCentralManager *centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
5. 将其作为属性保存为只要您需要更新:
self.centralManager = centralManager;

6. 实现此方法:

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
   if ([central state] == CBCentralManagerStatePoweredOff) {
       NSLog(@"Bluetooth off");
   }
   else if ([central state] == CBCentralManagerStatePoweredOn) {
       NSLog(@"Bluetooth on");
   }
}

现在尝试启用/禁用蓝牙并查看控制台以获取日志

于 2015-03-25T15:59:08.577 回答
0

实现CBCentralManagerDelegate协议。这是监控蓝牙的唯一方法,

在此处输入图像描述

于 2015-03-25T16:10:31.303 回答
-1

尝试:@"BluetoothConnectabilityChangedNotification"

我继承了注册这些通知的代码:

BluetoothAvailabilityChangedNotification
BluetoothConnectabilityChangedNotification
BluetoothPowerChangedNotification

并且每个应用程序都会调用该应用程序。

我不知道定义来自哪里。底层实现是发布这些。

于 2013-10-25T19:01:00.013 回答