How to ensure that open command invokes main funct

2019-09-14 03:47发布

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条回答
劫难
2楼-- · 2019-09-14 04:21

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.

查看更多
登录 后发表回答