2012-03-03 85 views
1

我的主要方法是打开一个应用程序,并在完成执行后将running设置为false,唯一的问题是我只想将running设置为false,已打开的应用已关闭。有没有简单的方法来做到这一点?java - 如何打开程序并检测程序何时关闭

这是我的代码:

Runtime runtime = Runtime.getRuntime(); 
boolean running = true; 
try { 
    Process p = runtime.exec("open test.app"); 
    p.waitFor(); 
} catch (InterruptedException e) {} 
running = false; 

编辑:会发生什么,此刻的是它开启test.app,然后设置running到,即使该应用程序仍在运行错误。

回答

1

似乎open启动应用程序并退出。所以你仍然可以看到一些正在运行的东西,而java看到这个过程已经完成我猜你是在MacOS上做的。我从来没有触摸自己的Mac电脑,但文档,你需要通过-W选项强制open等待应用程序终止open命令状态:Process p = runtime.exec("open -W test.app");

+0

非常感谢您的先生!我在Mac上运行,我甚至没有想到要查看“open”的手册页。再次感谢你 :) – troydayy 2012-03-03 13:48:16

2
/** 
* Detects when a process is finished and invokes the associated listeners. 
*/ 
public class ProcessExitDetector extends Thread { 

    /** The process for which we have to detect the end. */ 
    private Process process; 
    /** The associated listeners to be invoked at the end of the process. */ 
    private List<ProcessListener> listeners = new ArrayList<ProcessListener>(); 

    /** 
    * Starts the detection for the given process 
    * @param process the process for which we have to detect when it is finished 
    */ 
    public ProcessExitDetector(Process process) { 
     try { 
      // test if the process is finished 
      process.exitValue(); 
      throw new IllegalArgumentException("The process is already ended"); 
     } catch (IllegalThreadStateException exc) { 
      this.process = process; 
     } 
    } 

    /** @return the process that it is watched by this detector. */ 
    public Process getProcess() { 
     return process; 
    } 

    public void run() { 
     try { 
      // wait for the process to finish 
      process.waitFor(); 
      // invokes the listeners 
      for (ProcessListener listener : listeners) { 
       listener.processFinished(process); 
      } 
     } catch (InterruptedException e) { 
     } 
    } 

    /** Adds a process listener. 
    * @param listener the listener to be added 
    */ 
    public void addProcessListener(ProcessListener listener) { 
     listeners.add(listener); 
    } 

    /** Removes a process listener. 
    * @param listener the listener to be removed 
    */ 
    public void removeProcessListener(ProcessListener listener) { 
     listeners.remove(listener); 
    } 
} 

使用方法如下:

... 
processExitDetector = new ProcessExitDetector(program); 
processExitDetector .addProcessListener(new ProcessListener() { 
    public void processFinished(Process process) { 
     System.out.println("The program has finished."); 
    } 
}); 
processExitDetector.start(); 

来源(S)Detecting Process Exit in Java

+0

我试过了,它仍然具有相同的效果。它表示已完成,但已打开的应用程序仍在运行。我设置的程序等于'runtime.exec(“open test.app”)',这可能与它有关... – troydayy 2012-03-03 12:53:00

+0

yup,'open'将启动一个应用程序并立即返回。 – brettw 2012-03-04 02:57:23

相关问题