B4J Tutorial Non-UI Applications

B4J currently supports two types of applications: UI applications (based on JavaFX) and Non-UI applications.

Non-UI applications are standard Java applications. Usually the input to such applications is with command line arguments.

You should create a new project and select:

SS-2013-12-09_11.41.53.png


The program starts with:
B4X:
Sub AppStart(Args() As String)

End Sub

The program will end after this sub unless you call StartMessageLoop. Calling StartMessageLoop means that the main thread is now handling an internal message queue. This is useful if you need to wait for some other event to happen.

For example, we will create a very simple "curl" application. curl is a Linux app that allows you to send Http requests.

In this case the program will receive one argument which is the URL, it will download it and print the downloaded resource.

In order to test it we need to provide the command line argument. This is done with the #CommandLineArgs module attribute.

The complete code:
B4X:
'Non-UI application (console application)
#Region  Project Attributes
   #CommandLineArgs: http://www.b4x.com
#End Region

Sub Process_Globals
  
End Sub

Sub AppStart (Args() As String)
   If Args.Length = 0 Then
     Log("URL is missing.")
     ExitApplication2(1)
   End If
   Dim j As HttpJob
   j.Initialize("j", Me)
   j.Download(Args(0))
   StartMessageLoop
End Sub

Sub JobDone(Job As HttpJob)
   If Job.Success Then
     Log(Job.GetString)
   Else
     Log(Job.ErrorMessage)
   End If
   Job.Release
   ExitApplication2(0) 'exit the application. Without this call the program will just hang.
End Sub

The jar file created is not an executable jar. You need to run it by calling the java program.
The syntax is:
B4X:
java -cp <jar file> <package>.main <args>
You can create a batch file or script to run it.

SS-2013-11-19_09.43.36.png


Note that instead of referencing jHttpUtils2, we are using its source code. jHttpUtils2 library depends on jFX (for the GetBitmap method which is removed here).
 

Attachments

  • curl.zip
    2.8 KB · Views: 1,331
Last edited:

Cableguy

Expert
Licensed User
Longtime User
can a non-ui jar be converted into an executable?
 

Cableguy

Expert
Licensed User
Longtime User
For UI apps, i'v already used it, but never with non-UI ones...
 

mrred128

Active Member
Licensed User
Longtime User
On the "basic" config screen, there is an option to "Stay alive after launching a GUI application". To me, that would infer that a non-GUI application should be possible.
 
Top