开发者社区> 问答> 正文

如何使用Java特定于操作系统的通知?

我不是行业程序员(我拥有的所有Java知识都来自Hard Knocks学院)。请原谅我要问的愚蠢问题,并适当回答。

我正在使用的Java应用程序使用与平台无关的非常多的通知(例如成功下载文件时)。我想使用平台感知的通知。在Linux上发出通知的代码非常简单:

import org.gnome.gtk.Gtk;
import org.gnome.notify.Notify;
import org.gnome.notify.Notification;

public class HelloWorld
{
    public static void main(String[] args) {
        Gtk.init(args);
        Notify.init("Hello world");
        Notification Hello = new Notification("Hello world!", "This is an example notification.", "dialog-information");
        Hello.show();
    }
}

在Mac上,它有些复杂,但仍然可行:

interface NsUserNotificationsBridge extends Library {
    NsUserNotificationsBridge instance = (NsUserNotificationsBridge)
            Native.loadLibrary("/usr/local/lib/NsUserNotificationsBridge.dylib", NsUserNotificationsBridge.class);

    public int sendNotification(String title, String subtitle, String text, int timeoffset);
}

它需要一个可从以下github存储库获得的dylib:https : //github.com/petesh/OSxNotificationCenter

Windows的方式是这样的:

import java.awt.*;
import java.awt.TrayIcon.MessageType;

public class TrayIconDemo {

    public static void main(String[] args) throws AWTException {
        if (SystemTray.isSupported()) {
            TrayIconDemo td = new TrayIconDemo();
            td.displayTray();
        } else {
            System.err.println("System tray not supported!");
        }
    }

    public void displayTray() throws AWTException {
        //Obtain only one instance of the SystemTray object
        SystemTray tray = SystemTray.getSystemTray();

        //If the icon is a file
        Image image = Toolkit.getDefaultToolkit().createImage("icon.png");
        //Alternative (if the icon is on the classpath):
        //Image image = Toolkit.getDefaultToolkit().createImage(getClass().getResource("icon.png"));

        TrayIcon trayIcon = new TrayIcon(image, "Tray Demo");
        //Let the system resize the image if needed
        trayIcon.setImageAutoSize(true);
        //Set tooltip text for the tray icon
        trayIcon.setToolTip("System tray icon demo");
        tray.add(trayIcon);

        trayIcon.displayMessage("Hello, World", "notification demo", MessageType.INFO);
    }
}

关键是,我希望这些片段仅在适当的平台上执行;我不希望Java在Windows上编译GTK方法,因为它的依赖项不存在。

如何使Java识别它,就像“嘿,我正在为Mac系统编译,所以我正在使用Mac版本的代码”。

展开
收起
垚tutu 2019-12-04 17:13:55 687 0
0 条回答
写回答
取消 提交回答
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载