我不是一名程序员(我所拥有的任何 Java 知识都来自 School of 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 版本的代码。”
为了拥有简单、干净、没有额外依赖项的东西,我会放弃所有本机库,而是依赖本机程序,我确信这些程序保证(或至少可能)在每个各自的系统上可用:
String title = "Hello world!";
String message = "This is an example notification.";
Image image = ImageIO.read(getClass().getResource("icon.png"));
String os = System.getProperty("os.name");
if (os.contains("Linux")) {
ProcessBuilder builder = new ProcessBuilder(
"zenity",
"--notification",
"--text=" + title + "\\n" + message);
builder.inheritIO().start();
} else if (os.contains("Mac")) {
ProcessBuilder builder = new ProcessBuilder(
"osascript", "-e",
"display notification \"" + message + "\""
+ " with title \"" + title + "\"");
builder.inheritIO().start();
} else if (SystemTray.isSupported()) {
SystemTray tray = SystemTray.getSystemTray();
TrayIcon trayIcon = new TrayIcon(image, "Tray Demo");
trayIcon.setImageAutoSize(true);
tray.add(trayIcon);
trayIcon.displayMessage(title, message, TrayIcon.MessageType.INFO);
}