2012-03-03 24 views
1

私のmainメソッドは、アプリケーションを開き、実行が終了した後に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; 

EDIT:何の瞬間に起こることは、それはtest.appを開いている、それはアプリがまだ実行されているにもかかわらず、falseにrunningを設定します。

答えて

1

openアプリと終了を開始することと思われます。だからあなたはまだ何かが走っているのを見て、javaはそのプロセスが完了したと見ます。私はあなたがMacOSでやっていると思います。私はMacには一度も触れていませんが、のドキュメントでは、-Wオプションを強制的に渡す必要があると書かれています。Process p = runtime.exec("open -W test.app");

+0

ありがとうございました!私はMacで動いていて、 'open'のmanページを見ることさえ考えなかった。ありがとうございました :) – troydayy

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

+0

yup、 'open'はアプリケーションを起動してすぐに戻ります。 – brettw

関連する問題