Reputation: 88
I want to have a main application and a background application each in it's own JVM.
When launching the main it has to check if the background is running, and launch it if not.
I will have multiple mains running but I want only one background application.
It is fine for the background to keep running even after all mains are closed.
It's my first making a background application, I don't know:
I am still in the design phase, any comment or suggestion even remotely related is welcome.
I will be grateful if you can provide example code or a link.
Upvotes: 0
Views: 692
Reputation: 3537
From my understanding, you are looking for SingleInstance
application, and you don't want it to be terminate to perform some background process?
I don't understand The 3rd question, but I'm gonna give you straight answer for the first and second.
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
checkIfRunning(); //Check first if the Application is aready running.
Parent root = FXMLLoader.load(getClass().getResource("fxml/main.fxml"));
primaryStage.setTitle("Hello World");
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
Platform.setImplicitExit(false); //Prevent the Application from Terminating when it's close
}
public static void main(String[] args) {
launch(args);
}
/**The function for checking if the application is already running start here**/
private static final int PORT = 9999;
private static ServerSocket socket;
private static void checkIfRunning() {
try {
//Bind to localhost adapter with a zero connection queue
socket = new ServerSocket(PORT,0, InetAddress.getByAddress(new byte[] {127,0,0,1}));
}
catch (BindException e) {
System.err.println("Application already running.");
System.exit(1);
}
catch (IOException e) {
System.err.println("Unexpected error when checking if application is already running.");
e.printStackTrace();
System.exit(2);
}
}
}
try it and you'll notice when you close the application it will still running and you won't be able to start more than one of the application.
Upvotes: 1