我的main方法打开一个应用程序并在执行完成后将running
设置为false,唯一的问题是我只想在打开的应用程序关闭后将running
设置为false。有没有简单的方法呢?
这是我的代码:
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
设置为false。
答案 0 :(得分: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
答案 1 :(得分:1)
似乎open
启动应用并退出。所以你仍然看到正在运行的东西,java看到这个过程完成了。我猜你是在MacOS上做的。我自己从未触摸过Mac,但open
命令的文档说明您需要通过-W
选项强制open
等待应用终止:Process p = runtime.exec("open -W test.app");
答案 2 :(得分:0)
我希望每当我打开用net bean制作的应用程序时,都从我离开的地方开始,或者从上次登录的帐户开始。就像我们登录Facebook并保持登录状态,即使我们关闭该应用程序也是如此我们重新启动应用程序,看到已经登录。