2012-02-15 60 views
5

有没有办法知道我的设备(iPhone)何时插入电源,例如带有USB端口的电脑或汽车音响系统?我在我的应用中使用本地化服务,并且我想在设备插入时自动更改为kCLLocationAccuracyBestForNavigation。谢谢...如何知道iOS设备何时插入?

回答

3

您可以注册以在配件连接或断开连接时收到通知。

例子:

[[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications]; 
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 
[notificationCenter addObserver:self 
         selector:@selector(accessoryDidConnect:) 
          name:EAAccessoryDidConnectNotification 
         object:nil]; 
[notificationCenter addObserver:self 
         selector:@selector(accessoryDidDisconnect:) 
          name:EAAccessoryDidDisconnectNotification 
         object:nil]; 

一旦你收到此通知,您可以使用一个for循环遍历每个附件,如:

NSArray *accessories = [[EAAccessoryManager sharedAccessoryManager] connectedAccessories]; 
EAAccessory *accessory = nil; 

for (EAAccessory *obj in accessories) 
{ 
    // See if you're interested in this particular accessory 
} 

在某一点(的dealloc也许)你将要注销为这些通知。你可以做到这一点,如:

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 
[notificationCenter removeObserver:self 
           name:EAAccessoryDidDisconnectNotification 
          object:nil]; 
[notificationCenter removeObserver:self 
           name:EAAccessoryDidConnectNotification 
          object:nil]; 
[[EAAccessoryManager sharedAccessoryManager] unregisterForLocalNotifications]; 
+0

**非常感谢**我会tes t此代码... – human4 2012-02-16 21:21:54

+0

@ human4总是乐于提供帮助。如果'UIDevice'的'batteryState'上的KVO正常工作,那么这就是我想要的。 – Sam 2012-02-16 22:22:05

+0

这不再起作用。 – 2015-01-23 08:53:15

7

您可以启用电池监控直通的UIDevice class并检查电池状态,看它是否正在充电:

typedef enum { 
    UIDeviceBatteryStateUnknown, 
    UIDeviceBatteryStateUnplugged, 
    UIDeviceBatteryStateCharging, 
    UIDeviceBatteryStateFull, 
} UIDeviceBatteryState; 

你要检查或收费在启用最佳GPS准确性之前已满。通过让你自己的操作方法batteryStateChanged通话

UIDeviceBatteryState batteryState = [[UIDevice currentDevice] batteryState]; 

要订阅通知,关于电池状态的变化,例如:

- (void) setup { 
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; 
    NSNotificationCenter * center= [NSNotificationCenter defaultCenter]; 
    [center addObserver:self 
      selector:@selector(batteryStateChanged) 
       name:UIDeviceBatteryStateDidChangeNotification 
       object:nil]; 
} 

+1

+1在'UIDevice'的'batteryState'属性上做KVO似乎是OP想要做的最好的方式。 – Sam 2012-02-15 21:04:38

+0

**非常感谢**我会测试此代码... – human4 2012-02-16 21:21:37

2

要检查电池状态记得取消订阅当你的对象是dealloced:

- (void) dealloc 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:NO]; 
} 
相关问题