如何以编程方式获取iphone中蓝牙(ON / OFF)的状态

时间:2011-02-10 08:53:26

标签: ios iphone bluetooth iobluetooth

我试图以编程方式获取iPhone / iPod蓝牙的状态,无论是开启还是关闭。 是否可以使用某些Apple API或第三方API。

7 个答案:

答案 0 :(得分:46)

Sam's answer的一些研究,我认为我会分享 你可以在不使用私有API的情况下这样做,但需要注意几点:

  • 仅适用于iOS 5.0+
  • 它只适用于那些设备 支持蓝牙LE规格(iPhone 4S +,第5代iPod +,iPad 第3代+)
  • 简单地分配类将导致您的应用程序请求允许使用用户的蓝牙堆栈(可能不需要),如果他们拒绝,您唯一能看到的就是CBCentralManagerStateUnauthorized iOS7 +版本:现在可以防止前面提到的删除,请参阅下面的注释this answer,它解释了您可以将CoreBluetooth的CBCentralManagerOptionShowPowerAlertKey选项设置为NO以防止权限提示。
  • 蓝牙状态的检索是异步的,并且是连续的。您将需要设置委托以获取状态更改,因为检查新分配的蓝牙管理器的状态将返回CBCentralManagerStateUnknown

话虽这么说,这种方法似乎确实提供了蓝牙堆栈状态的实时更新。

包含CoreBluetooth框架后,

#import <CoreBluetooth/CoreBluetooth.h>

这些测试很容易使用:

- (void)detectBluetooth
{
    if(!self.bluetoothManager)
    {
        // Put on main queue so we can call UIAlertView from delegate callbacks.
        self.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
    }
    [self centralManagerDidUpdateState:self.bluetoothManager]; // Show initial state
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSString *stateString = nil;
    switch(self.bluetoothManager.state)
    {
        case CBCentralManagerStateResetting: stateString = @"The connection with the system service was momentarily lost, update imminent."; break;
        case CBCentralManagerStateUnsupported: stateString = @"The platform doesn't support Bluetooth Low Energy."; break;
        case CBCentralManagerStateUnauthorized: stateString = @"The app is not authorized to use Bluetooth Low Energy."; break;
        case CBCentralManagerStatePoweredOff: stateString = @"Bluetooth is currently powered off."; break;
        case CBCentralManagerStatePoweredOn: stateString = @"Bluetooth is currently powered on and available to use."; break;
        default: stateString = @"State unknown, update imminent."; break;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Bluetooth state"
                                                     message:stateString
                                                    delegate:nil
                                          cancelButtonTitle:@"ok" otherButtonTitles: nil];
    [alert show];
}

答案 1 :(得分:23)

要禁用默认警报消息,只需在实例化CBPeripheralManager时通过选项字典:

SWIFT在iOS8 +上测试

import CoreBluetooth

//Define class variable in your VC/AppDelegate
var bluetoothPeripheralManager: CBPeripheralManager?

 //On viewDidLoad/didFinishLaunchingWithOptions
let options = [CBCentralManagerOptionShowPowerAlertKey:0] //<-this is the magic bit!
bluetoothPeripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: options)

显然你还需要实现CKManagerDelegate委托方法peripManagerDidUpdateState,如上所述:

func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!) {

    var statusMessage = ""

    switch peripheral.state {
    case .poweredOn:
        statusMessage = "Bluetooth Status: Turned On"

    case .poweredOff:
        statusMessage = "Bluetooth Status: Turned Off"

    case .resetting:
        statusMessage = "Bluetooth Status: Resetting"

    case .unauthorized:
        statusMessage = "Bluetooth Status: Not Authorized"

    case .unsupported:
        statusMessage = "Bluetooth Status: Not Supported"

    case .unknown:
        statusMessage = "Bluetooth Status: Unknown"
    }

    print(statusMessage)

    if peripheral.state == .poweredOff {
        //TODO: Update this property in an App Manager class
    }
}

答案 2 :(得分:10)

此答案已从最初的Objective-C更新为Swift 4.0。

假设您已经创建了蓝牙管理器并将委托分配给ViewController类。

import CoreBluetooth

extension ViewController : CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .poweredOn:
            print("powered on")
        case .poweredOff:
            print("powered off")
        case .resetting:
            print("resetting")
        case .unauthorized:
            print("unauthorized")
        case .unsupported:
            print("unsupported")
        case .unknown:
            print("unknown")
        }
    }
}

答案 3 :(得分:5)

有关BadPirate答案的一些更新,使用iOS7,您可以设置中央管理器在分配管理器对象时不显示警告,方法是为其提供一个键“CBCentralManagerOptionShowPowerAlertKey”设置为0的NSDictionary。

self.cbManager = [[CBCentralManager alloc] initWithDelegate:self
                                                          queue:nil
                                                        options:
                      [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0]
                                                  forKey:CBCentralManagerOptionShowPowerAlertKey]];

答案 4 :(得分:2)

使用CoreBluetooth在iOS 5及更高版本上有一种方法。您可以使用的类是CBCentralManager。它有一个属性“状态”,您可以检查蓝牙是否打开。 (枚举CBCentralManagerState具有您要检查的值)。

答案 5 :(得分:1)

设置为CBCentralManager后,您可以从delegate method或直接使用CBCentralManager::stateCBCentralManager::authorization

import CoreBluetooth

class Manager {
    let centralManager = CBCentralManager(delegate: self, queue: nil)

    var isBTTurnedOn: Bool {
        return centralManager.state == .poweredOn
    }

    var isAuthorized: Bool {
        if #available(iOS 13.0, *) {
            return centralManager.authorization == .allowedAlways
        } else {
            return true
        }
    }
}

答案 6 :(得分:0)

这个解决方案有点旧,在苹果推出核心蓝牙之前

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        // Override point for customization after application launch.


        Class BluetoothManager = objc_getClass( "BluetoothManager" ) ;
        id btCont = [BluetoothManager sharedInstance] ;
        [self performSelector:@selector(status:) withObject:btCont afterDelay:1.0f] ;

        return YES ;
    }


    - (void)status:(id)btCont
    {
        BOOL currentState = [btCont enabled] ;
        //check the value of currentState 

    }