B4J Code Snippet Run B4J console app

Depends on jShell. Tested on Windows. Expected to work on Mac and Linux as well.
This code will not work when called from a standalone package. More powerful implementation is available here: https://www.b4x.com/android/forum/threads/jarcaller-run-and-kill-non-ui-jars.168284/

B4X:
'Jar - Path to the compiled jar file. Should be a non-ui / console app.
'Args - Optional string arguments.
Private Sub RunJar(Jar As String, Args As List)
    Dim shl As Shell
    Dim javaExe As String = File.Combine(GetSystemProperty("java.home", ""), "bin/java")
    Dim NewArgs As List
    NewArgs.Initialize
    NewArgs.Add("-jar")
    NewArgs.Add(Jar)
    If Initialized(Args) Then NewArgs.AddAll(Args)
    shl.Initialize("shl", javaExe, NewArgs)
    shl.WorkingDirectory = File.GetFileParent(Jar)
    shl.Run(-1)
    Wait For shl_ProcessCompleted (Success As Boolean, ExitCode As Int, StdOut As String, StdErr As String)
    Log(StdOut)
    Log(StdErr)
End Sub

Usage example:
B4X:
RunJar("C:\Users\H\Downloads\projects\ccc\Objects\ccc.jar", Array("aaa", "bbb", "ccc"))
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
If you want to call this method and wait for the process to complete:
1. Change signature to:
B4X:
Private Sub RunJar(Jar As String, Args As List) As ResumableSub
2. Add to the sub:
B4X:
Return Success And ExitCode = 0 'depending on the process you are calling...

Usage:
B4X:
Wait For (RunJar(...)) Complete (Success As Boolean)
 
Last edited:

aeric

Expert
Licensed User
Longtime User
Is it missing As ResumableSub?
 

marcick

Well-Known Member
Licensed User
Longtime User
Interesting. I would need this also, Is it difficult to implement?
  1. check if the JAR is already running
  2. kill the JAR before restart
I spent a morning with ChatGpt with tons of solutions and nothing working ........
 

Chris2

Active Member
Licensed User
Longtime User
Interesting. I would need this also, Is it difficult to implement?
  1. check if the JAR is already running
  2. kill the JAR before restart
I spent a morning with ChatGpt with tons of solutions and nothing working ........
 

marcick

Well-Known Member
Licensed User
Longtime User
That's good and works perfect. But how to use those commands inside B4J instead of a cmd line?
 

Chris2

Active Member
Licensed User
Longtime User
That's good and works perfect. But how to use those commands inside B4J instead of a cmd line?
You should really start a new question for this in the Questions forum as it's not specifically realated to this thread's code snippet.
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…