【问题标题】:How to get notified before Mac goes to sleep using Cocoa listing?如何使用 Cocoa 列表在 Mac 进入睡眠状态之前获得通知?
【发布时间】:2021-06-16 15:50:48
【问题描述】:

我正在开发一个 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];

}

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

【问题讨论】:

  • [只是好奇] 你为什么用 Objective-c 为什么不用 Swift?
  • 这是我在 Mac 中搜索接收睡眠通知时遇到的代码。这个代码是根据苹果开发者网站 (developer.apple.com/library/archive/qa/qa1340/_index.html) 和关于 Swift 的,这个应用程序不是我开发的,我只是在开发它。

标签: java objective-c macos sleep nsworkspace


【解决方案1】:

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

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

了解如何使用启动守护程序甚至是

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

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

【讨论】:

  • 你第一个分享的链接,我很久以前就遇到过,但不知道如何处理它,因为它是客观的c代码,看起来好像没有头或尾.至少如果你能解释它是如何作为一个单独的类单独工作的就好了。
  • 试试清单3——它是独立的,你可以复制粘贴编译运行。
猜你喜欢
  • 2012-11-12
  • 1970-01-01
  • 2011-09-08
  • 1970-01-01
  • 2020-05-18
  • 2018-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多