我正在编写一种在插入/拔出 USB 设备时从操作系统接收通知的方法。我在这个问题上使用了建议
如何知道何时在 Cocoa 中连接了 HID USB/蓝牙设备?.
这就是我所拥有的:
io_iterator_t portIterator;
CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName); // Interested in instances of class
long vendorID = usbVendorId;
long productID = usbProductID;
// Create a CFNumber for the idVendor and set the value in the dictionary
CFNumberRef numberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &vendorID);
CFDictionarySetValue(matchingDict, CFSTR(kUSBVendorID), numberRef);
CFRelease(numberRef);
// Create a CFNumber for the idProduct and set the value in the dictionary
numberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &productID);
CFDictionarySetValue(matchingDict, CFSTR(kUSBProductID), numberRef);
CFRelease(numberRef);
numberRef = NULL;
mach_port_t masterPort;
IOMasterPort(MACH_PORT_NULL, &masterPort);
// Set up notification port and add it to the current run loop for addition notifications.
IONotificationPortRef notificationPort = IONotificationPortCreate(masterPort);
CFRunLoopAddSource(CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource(notificationPort),
kCFRunLoopDefaultMode);
// Register for notifications when a serial port is added to the system.
// Retain dictionary first because all IOServiceMatching calls consume dictionary.
CFRetain(matchingDict);
kern_return_t result = IOServiceAddMatchingNotification(notificationPort,
kIOMatchedNotification,
matchingDict,
usbDeviceAdded,
nil,
&portIterator);
// Run out the iterator or notifications won't start.
while (IOIteratorNext(portIterator)) {};
// Also Set up notification port and add it to the current run loop removal notifications.
IONotificationPortRef terminationNotificationPort = IONotificationPortCreate(kIOMasterPortDefault);
CFRunLoopAddSource(CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource(terminationNotificationPort),
kCFRunLoopDefaultMode);
// Register for notifications when a serial port is added to the system.
// Retain dictionary first because all IOServiceMatching calls consume dictionary.
CFRetain(matchingDict);
kern_return_t result1 = IOServiceAddMatchingNotification(terminationNotificationPort,
kIOTerminatedNotification,
matchingDict,
usbDeviceRemoved,
this,
&portIterator);
// Run out the iterator or notifications won't start.
while (IOIteratorNext(portIterator)) {};
CFRetain(matchingDict);
我遇到了与原始海报相同的问题。我收到通知,但只有一次用于删除/添加。如果我尝试添加/删除不同的设备并不重要,我只会收到一个通知。在那之后,我只是没有得到通知。
有人可以帮我弄清楚为什么会发生这种情况。谢谢!