Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

java - Desktop.getDesktop().browse Hangs

I'm working on an application in which if a user clicks on a link, I want it to open in their default browser. From what I've read, this should in theory work, however, when run on Linux (specifically Linux Mint 17.1), it hangs until the program is force-quit. I'm not particularly interested in having it open in WebView. Any alternatives or fixes that you all can think of? Thanks in advance.

if(Desktop.isDesktopSupported()){
    try{
       Desktop.getDesktop().browse(new URI(url));
    }catch (IOException | URISyntaxException e){
       log.debug(e);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm using Ubuntu 16.04 and I have the same hang when using Desktop.getDesktop().browse(). Here is the workaround that I'm using:

public void browseURL(String urlString) {

    try {
        if (SystemUtils.IS_OS_LINUX) {
            // Workaround for Linux because "Desktop.getDesktop().browse()" doesn't work on some Linux implementations
            if (Runtime.getRuntime().exec(new String[] { "which", "xdg-open" }).getInputStream().read() != -1) {
                Runtime.getRuntime().exec(new String[] { "xdg-open", urlString });
            } else {
                showAlert("Browse URL", "xdg-open not supported!", true);
            }
        } else {
            if (Desktop.isDesktopSupported())
            {
                Desktop.getDesktop().browse(new URI(urlString));
            } else {
                showAlert("Browse URL", "Desktop command not supported!", true);
            }
        }

    } catch (IOException | URISyntaxException e) {
        showAlert("Browse URL", "Failed to open URL " + urlString , true);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...