我不是专业的程序员(我所掌握的任何 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 版本的代码。”