开发者社区 问答 正文

如何使用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 747 分享 版权
阿里云 AI 助理回答

在Java中,实现平台感知的代码执行通常涉及使用条件编译或者运行时检查操作系统类型。你可以通过以下几种方式来实现:

1. 使用java.lang.System.getProperty("os.name")

在运行时检测操作系统名称,并据此选择不同的通知实现。

String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
    // Windows code here
} else if (os.contains("mac")) {
    // Mac code here
} else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
    // Linux code here
} else {
    // Other OS, or error handling
}

2. 抽象类或接口 + 实现类

定义一个抽象类或接口表示通知服务,然后为每个平台创建具体的实现类。

public interface NotificationService {
    void sendNotification(String title, String message);
}

// Windows Implementation
public class WindowsNotificationService implements NotificationService {
    @Override
    public void sendNotification(String title, String message) {
        // Windows specific implementation
    }
}

// MacOS Implementation
public class MacOSNotificationService implements NotificationService {
    @Override
    public void sendNotification(String title, String message) {
        // MacOS specific implementation
    }
}

// Linux Implementation
public class LinuxNotificationService implements NotificationService {
    @Override
    public void sendNotification(String title, String message) {
        // Linux specific implementation
    }
}

然后,在应用启动时根据系统类型实例化相应的实现类。

NotificationService notificationService;
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
    notificationService = new WindowsNotificationService();
} else if (os.contains("mac")) {
    notificationService = new MacOSNotificationService();
} else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
    notificationService = new LinuxNotificationService();
} else {
    throw new UnsupportedOperationException("Unsupported operating system.");
}

notificationService.sendNotification("Title", "Message");

3. 使用第三方库

考虑使用成熟的第三方库,如JavaFX的通知API(如果您的应用程序可以使用JavaFX),或者像java-notify这样的库,它已经封装了跨平台通知的功能,减少了你需要写的代码量。

注意事项

  • 确保在不同平台上所需的依赖项正确管理。对于Mac和Linux上的本地库,可能需要打包时包含这些特定于平台的库。
  • 考虑到可维护性和兼容性,尽量采用标准的、广泛支持的解决方案。
  • 如果你的项目是Maven或Gradle项目,确保配置好对应的依赖管理和构建脚本,以便在不同平台上正确处理依赖。
有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答