How to ensure that open command invokes main function in the Java application on Mac

寵の児 提交于 2019-12-25 02:50:08

问题


I have a java application on Mac that was built in Eclipse, and bundled by using a maven plugin named osxappbundle-maven-plugin. After I unpack the dmg file of the application, obtain an App file, and copy it to my hard drive, I invoke this App through a terminal by using the following command: open -a "/Full/Path/To/App/Match Player.app" --args "/Full/Path/To/File/TEST 1.mplx"

This opens the application correctly.
However, after I execute the following command: open -a "/Full/Path/To/App/Match Player.app" --args "/Full/Path/To/File/TEST 2.mplx" my application does not open the application with the new test file, but just focuses the window of the previously opened application.
I am quite sure that the main function is not invoked again, since I wrote the main function such that on every invocation, it re-initializes the windows. (thus the application should re-initialize fully).

Opening multiple applications by using "open -n" option is not an option.


回答1:


I am quite sure that the main function is not invoked again

Yes, when there's already an instance of the application running, the "open" command simply sends an "open files" event to the running instance. You need to register an OpenFilesHandler to receive this event, and you could call main again from inside the handler.

import com.apple.eawt.*;

public class MyMainClass {
  private static boolean listenerRegistered = false;

  public static void main(String[] args) throws Exception {
    if(!listenerRegistered) {
      Application.getApplication().setOpenFileHandler(new OpenFilesHandler() {
        public void openFiles(AppEvent.OpenFilesEvent evt) {
          List<String> filenames = new ArrayList<String>();
          for(File f : evt.getFiles()) {
            filenames.add(f.getAbsolutePath());
          }
          MyMainClass.main(filenames.toArray(new String[filenames.size()]));
        }
      });
      listenerRegistered = true;
    }

    // rest of main goes here
  }
}

Now open -a "/Full/Path/To/App/Match Player.app" "/Full/Path/To/File/TEST 1.mplx" (without the --args) should do the right thing.



来源:https://stackoverflow.com/questions/15658255/how-to-ensure-that-open-command-invokes-main-function-in-the-java-application-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!