Android Tutorial Inline Java Code

The next versions of B4A (4.30) and B4J (2.80) will allow you to embed Java code inside your B4X code. B4i supports similar feature with Objective C.

The purpose of this feature is to make it easier to access third party SDKs and also to allow developers to add existing Java code snippets to their projects.

Adding Java code is done with an #If Java block:
B4X:
#If JAVA
public String FirstMethod() {
   return "Hello World!";
}
#End If

You need an instance of JavaObject to access the Java methods:
B4X:
Sub Process_Globals
   Private NativeMe As JavaObject
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
   If FirstTime Then
     NativeMe.InitializeContext
   End If
   Dim s As String = NativeMe.RunMethod("FirstMethod", Null)
   Log(s) 'will print Hello World!
End Sub
The Java code can also include imports. The compiler will find these imports and add them at the top of the class.

The Java code will be added at the end of the class. Right before the closing bracket.

Methods added to Activity or Service modules will be executed with the component context ('this' will be the activity or service instance).

Hooks

Hooks are similar to the standard events but they run Java methods. Hooks are mainly used by SDKs that require you to add code in the various Activity events.
Note that there are no hooks in B4J implementation.

For example the following code will run in the standard Activity onCreate method (before the call to setContentView):
B4X:
#If JAVA
public void _onCreate() {
   requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
}
#End If

Activity hooks:
_onCreate()
_onResume()
_onPause()
_onDestroy()
_onStop()
_onStart()
_onPrepareOptionsMenu (android.view.Menu menu)
_onnewintent (android.content.Intent intent)
boolean _onCreateOptionsMenu (android.view.Menu menu) <--- If you return true from this method then the standard B4A code in onCreateOptionsMenu will not run.
boolean _onkeydown (int keyCode, android.view.KeyEvent event) <-- Return true from this method to return true from the native onKeyDown (and skip Activity_KeyPress event).
boolean _onkeyup (int keyCode, android.view.KeyEvent event) <-- same comment as above

Service hooks:
_onCreate()
_onStartCommand(Intent intent, int flags, int startId)
_onDestroy()

Tips

- The methods you add should be public methods.
- Methods in static code modules should be public static.
- See the attached project. It shows how to call Java methods in all types of modules.

Don't misuse this feature. There are no performance advantages for using it and it can make your project more difficult to debug and maintain.
 

Attachments

  • InlineJava.zip
    12.7 KB · Views: 4,257
  • B4J-InlineJava.zip
    1.2 KB · Views: 2,590
Last edited:

Myr0n

Active Member
Licensed User
Longtime User
With this new addition, we could wrap a jar file inside of our b4a app without needed to wrapped in a library?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User

somed3v3loper

Well-Known Member
Licensed User
Longtime User
What are advantages of In-line Java code over using JavaObject way in accessing libraries ?
 

espi

Member
Licensed User
Longtime User
What is your question? Why wouldnt it be possible?

thank you for your time,
Can you give me a hint in instruction how this must be done, please:
the string example i understand,
how must this done with alert,, dialog,,

B4X:
Sub Process_Globals   
Private NativeMe As JavaObject
End Sub
' ..
' OK

Sub Globals
End Sub

Sub Activity_Create(FirstTime As Boolean)   
If FirstTime Then    
 NativeMe.InitializeContext   
End If   

' OK
' how must this involded

Dim s As String = NativeMe.RunMethod("FirstMethod", Null)   
Log(s) 'will print Hello World!
End Sub
' ok for the string hello world i understand..
' how must this be done example for alert

thank you very much!

espi
 

Devv

Active Member
Licensed User
Longtime User
Time to learn JAVA :D
thanks Erel you are a hard worker :cool:
 

wonder

Expert
Licensed User
Longtime User
I had some pretty nice games in .jar format for my old Nokias. Is it any possible to run those games on Android using this (or any other) method?
 

thedesolatesoul

Expert
Licensed User
Longtime User
I had some pretty nice games in .jar format for my old Nokias. Is it any possible to run those games on Android using this (or any other) method?
Not the J2ME and other platform specific portions. You can call pura java functions though.
 

corwin42

Expert
Licensed User
Longtime User
Great feature.

Just added these lines to a sample project:
B4X:
#If Java

    public boolean _onCreateOptionsMenu(android.view.Menu menu) {
    if (processBA.subExists("activity_createmenu")) {
        processBA.raiseEvent2(null, true, "activity_createmenu", false, new de.amberhome.objects.appcompat.ACMenuWrapper(menu));
        return true;
    }
    else
        return false;
}
#End If

Sub Activity_CreateMenu(Menu As ACMenu)
    Log("Initialize the Menu")
   
    Dim xml As XmlLayoutBuilder
    #IgnoreWarnings: 11
    Dim item As ACMenuItem
    Menu.Add2(10, 1, "Plus one", xml.GetDrawable("ic_plus_one_black_24dp")).ShowAsAction = item.SHOW_AS_ACTION_ALWAYS
    Menu.Add2(20, 2, "Refresh", xml.GetDrawable("ic_refresh_black_24dp")).ShowAsAction = item.SHOW_AS_ACTION_ALWAYS

    Menu.Add(1, 3, "Overflow1", Null)
    Menu.Add(2, 4, "Overflow2", Null)
    Menu.Add(3, 5, "Overflow3", Null)
   
    ToolBar.InitMenuListener
End Sub
Seems that this is all you have to do to use the menus of the AppCompat library in combination with a ToolBar.
 

espi

Member
Licensed User
Longtime User
You are confusing Java with JavaScript. There is no 'alert' method in Java.

Yes you are right Erel, sorry for confuse,
i mean with alert example a xy message .. not specific .. . ok my question
is it possible for import a java package like this and call the showMessage Dialog?

I test it with pure Java ( calc ) - this Inline is like a charme
but i think the inline is not for other packages ? or yes?
txs

B4X:
# if JAVA

// is it likewise possible?
import javax.swing.JOptionPane;

public void simpletest(){
JOptionPane.showMessageDialog(null, "Hello World");
}

...

// this is understand and run perfect
// no import
//
// DIM values as String  = NativeMe.RunMethod("calc",Null)
// Log(values)

public int calc() {
return 2*3;
}

#end if
 

espi

Member
Licensed User
Longtime User
javax.swing API is not included in Android SDK.

Hi Erel,

cheers

ok i have understand principal.
Great work!

greetings
espi


B4X:
Sub Activity_Create(FirstTime As Boolean)
	'Do not forget to load the layout file created with the visual designer. For example:
	Activity.LoadLayout("x")
	If FirstTime Then
	NativeMe.InitializeContext
	End If
End Sub

..
..


#If JAVA

import android.app.AlertDialog;

// import android.content.BroadcastReceiver;
// import android.content.Context;
// import android.content.Intent;
// import android.os.Bundle;
// import android.content.DialogInterface;
// import android.app.Activity;


public void txs() { 

AlertDialog.Builder builder = new AlertDialog.Builder(this);
 builder.setTitle("You Are Welcome")
		.setMessage("Txs for Inline Erel ;-)")
		.setNeutralButton("Ok", null);
AlertDialog dialog = builder.create();
dialog.show();
}
#end if



Sub Button1_Down
		NativeMe.RunMethod("txs", Null)
End Sub
 
Top