如何使用 Cocoa 列表在 Mac 进入睡眠状态之前获得通知?

问题描述

我正在开发一个 Java 应用程序,我需要使用以下代码在它休眠之前接收休眠通知

以下是 Apple Developer's site 建议的用于在睡眠前接收睡眠通知代码,我需要将此代码与我的 java 应用程序集成才能这样做。

- (void) receiveSleepNote: (NSNotification*) note

{

    NSLog(@"receiveSleepNote: %@",[note name]);

}

 

- (void) receiveWakeNote: (NSNotification*) note

{

    NSLog(@"receiveWakeNote: %@",[note name]);

}

 

- (void) fileNotifications

{

    //These notifications are filed on NSWorkspace's notification center,not the default

    // notification center. You will not receive sleep/wake notifications if you file

    //with the default notification center.

    [[[NSWorkspace sharedWorkspace] notificationCenter] addobserver: self

            selector: @selector(receiveSleepNote:)

            name: NSWorkspaceWillSleepNotification object: NULL];

 

    [[[NSWorkspace sharedWorkspace] notificationCenter] addobserver: self

            selector: @selector(receiveWakeNote:)

            name: NSWorkspaceDidWakeNotification object: NULL];

}

代码在我看来就像没有头没有尾的东西,我觉得很难理解。即使有人能解释这段代码是如何单独工作的,那也会让我受益匪浅。

解决方法

您可以为此尝试启动守护程序。参见例如

https://developer.apple.com/library/archive/qa/qa1340/_index.html

对于一些可以实现并用于与 Java 程序交互的 Objective-C 代码或

https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html

关于如何使用 Launch Daemons 或什至做到这一点

https://apple.stackexchange.com/questions/120321/is-there-a-way-to-make-launchd-stop-a-service-on-sleep-and-start-it-up-again-on

对于看起来与您相似的东西。