您实际上可以使用公共 API 来做到这一点。见this answer on stack overflow。
请注意,您可能需要检查电池状态是Charging 还是Full。两者都意味着电缆已插入。
另外,如果您从 Cydia 下载 notificationWatcher 实用程序(Erica Utilities 的一部分),并在越狱的 iPhone(通过 Wifi 和 SSH 连接)上运行它,您会在连接/断开 USB 电缆时的控制台:
截获通知:com.apple.springboard.fullycharged
截获通知:com.apple.springboard.pluggedin
截获通知:com.apple.springboard.fullycharged
所以,我猜你可以通过以下两种方式之一注册通知:
[[UIDevice currentDevice] setBatteryMonitoringEnabled: YES];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(batteryStatus)
name: UIDeviceBatteryStateDidChangeNotification
object: nil];
或者,使用 Core Foundation 通知:
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
NULL, // observer
plugStatus, // callback
CFSTR("com.apple.springboard.pluggedin"), // name
NULL, // object
CFNotificationSuspensionBehaviorHold);
然后回调函数可以是:
- (void) batteryStatus {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle: @"batteryStatus" message: @"battery" delegate: self cancelButtonTitle: @"Ok" otherButtonTitles: nil];
[alert show];
}
static void plugStatus(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle: @"plugStatus" message: @"plug" delegate: nil cancelButtonTitle: @"Ok" otherButtonTitles: nil];
[alert show];
if (userInfo != nil) {
CFShow(userInfo);
}
}
com.apple.springboard.pluggedin 在电缆插入时发送,或拔出。