You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Kotlin代码检测MacOS屏幕是否处于锁定状态?

在Kotlin中实现MacOS后台屏幕锁定监测应用

实现步骤

1. 环境准备

  • 安装Xcode(提供MacOS系统API的头文件与编译工具链)
  • 用IntelliJ IDEA创建Kotlin Native项目(选择「Native | Application」模板)

2. 核心功能:检测屏幕锁定状态

MacOS通过CoreGraphics框架的CGSSessionCopyCurrentDictionary()接口暴露屏幕锁定状态,Kotlin可直接调用该C API获取状态:

import platform.CoreGraphics.CGSSessionCopyCurrentDictionary
import platform.Foundation.NSDictionary

fun isScreenLocked(): Boolean {
    val sessionDict = CGSSessionCopyCurrentDictionary() as? NSDictionary
    // 从会话字典中提取锁定状态标识
    return sessionDict?.valueForKey("CGSSessionScreenIsLocked") as? Boolean ?: false
}

3. 定期检测与结果记录

用协程实现定时检测逻辑,并将结果写入用户目录下的日志文件(适合后台运行场景):

import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import platform.Foundation.NSDate
import platform.Foundation.NSHomeDirectory
import platform.Foundation.NSString
import platform.Foundation.NSURL
import platform.Foundation.NSUTF8StringEncoding

fun main() = runBlocking {
    val logPath = "~/Library/Logs/ScreenLockMonitor.log".expandTilde()
    val logFileURL = NSURL.fileURLWithPath(logPath)

    while (true) {
        val isLocked = isScreenLocked()
        val timestamp = NSDate().description
        val logEntry = "$timestamp - 屏幕状态:${if (isLocked) "已锁定" else "未锁定"}"
        
        // 追加写入日志
        val existingContent = NSString.stringWithContentsOfFile(
            logFileURL.path,
            encoding = NSUTF8StringEncoding,
            error = null
        ) ?: ""
        val newContent = existingContent + logEntry + "\n"
        newContent.writeToFile(
            logFileURL.path,
            atomically = true,
            encoding = NSUTF8StringEncoding,
            error = null
        )
        
        // 每隔30秒检测一次,可按需调整间隔
        delay(30000)
    }
}

// 解析路径中的~符号为用户主目录
fun String.expandTilde(): String {
    return if (startsWith("~")) {
        NSHomeDirectory() + substring(1)
    } else this
}

4. 配置为后台服务

MacOS用户级后台服务通过Launch Agent管理,创建plist配置文件(命名为com.yourname.ScreenLockMonitor.plist):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.yourname.ScreenLockMonitor</string>
    <key>ProgramArguments</key>
    <array>
        <!-- 替换为你的Kotlin可执行文件路径 -->
        <string>/Users/你的用户名/项目目录/build/bin/macosX64/releaseExecutable/项目名.kexe</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <!-- 重定向标准输出/错误到日志文件 -->
    <key>StandardOutPath</key>
    <string>~/Library/Logs/ScreenLockMonitor.out.log</string>
    <key>StandardErrorPath</key>
    <string>~/Library/Logs/ScreenLockMonitor.err.log</string>
</dict>
</plist>

将plist文件放到~/Library/LaunchAgents/目录下,通过终端命令管理服务:

  • 加载服务:launchctl load ~/Library/LaunchAgents/com.yourname.ScreenLockMonitor.plist
  • 启动服务:launchctl start com.yourname.ScreenLockMonitor
  • 停止服务:launchctl stop com.yourname.ScreenLockMonitor
  • 卸载服务:launchctl unload ~/Library/LaunchAgents/com.yourname.ScreenLockMonitor.plist

注意事项

  • 权限配置:前往系统偏好设置→安全性与隐私→隐私→后台App,确保应用被允许在后台运行
  • 编译可执行文件:在项目根目录执行./gradlew assemble,生成的可执行文件在build/bin/macosX64/releaseExecutable/路径下
  • 日志查看:可通过tail -f ~/Library/Logs/ScreenLockMonitor.log实时查看监测记录

内容的提问来源于stack exchange,提问作者Zeemee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 01:16:15