2012-03-03 113 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

相關問題