Blog

osx の notification を kotlin で呼びたい

osascript で呼ぶのがいいかな。apple script の escape 方法はよくわからないので JavaScript で書くことにして、 JSON で serialize して渡すのが良さそう。

fun sendNotification(message: String, title: String=message, subtitle: String=message, soundName: String = "Frog") {
    // https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/DisplayNotifications.html
    val params = jsonObject(
            "withTitle" to title,
            "subtitle" to subtitle,
            "soundName" to soundName
    )

    Runtime.getRuntime().exec(arrayOf(
            "osascript",
            "-l",
            "JavaScript",
            "-e",
            """var app = Application.currentApplication();
                app.includeStandardAdditions = true
                app.displayNotification(${message.toJson()}, $params)"""
    ))
}

JSON serialize は kotoson が便利。

compile 'com.github.salomonbrys.kotson:kotson:2.5.0'

で、こういうのちょっと頑張って書いてみたけど、LINE Notify 使うのが便利っぽいって話になった。。