Android Tutorial Inline Java Code

Discussion in 'Tutorials & Examples' started by Erel, Feb 2, 2015.

  1. Erel

    Erel Administrator Staff Member Licensed User

    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:
    Code:
    #If JAVA
    public String FirstMethod() {
       return "Hello World!";
    }
    #End If
    You need an instance of JavaObject to access the Java methods:
    Code:
    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):
    Code:
    #If JAVA
    public void _onCreate() {
       requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    }
    Activity hooks:
    _onCreate()
    _onResume()
    _onPause()
    _onDestroy()
    _onStop()
    _onStart()
    _onPrepareOptionsMenu (android.view.Menu menu)
    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.
     

    Attached Files:

    Last edited: Oct 6, 2016
    souzafo, zjd444, Devan and 122 others like this.
  2. Erel

    Erel Administrator Staff Member Licensed User

    Thank you. Please use the Like button instead of making "thank you" posts...
     
    ferya1, stari, jamesnz and 9 others like this.
  3. Myron

    Myron Member Licensed User

    With this new addition, we could wrap a jar file inside of our b4a app without needed to wrapped in a library?
     
  4. Erel

    Erel Administrator Staff Member Licensed User

  5. somed3v3loper

    somed3v3loper Well-Known Member Licensed User

    What are advantages of In-line Java code over using JavaObject way in accessing libraries ?
     
  6. thedesolatesoul

    thedesolatesoul Expert Licensed User

    Formatting and readability.
     
    somed3v3loper and NJDude like this.
  7. Erel

    Erel Administrator Staff Member Licensed User

    JavaObject is useful if you want to access a method or two. It quickly becomes cumbersome with more complicated code.

    Inline Java is simpler as you can just copy existing java code and is much more powerful.
     
  8. espi

    espi Member Licensed User

    is this possible too:

    Code:
    #If JAVA
    public void _onCreate() { 
     alert("hello") ; 
    }
    txs
     
  9. thedesolatesoul

    thedesolatesoul Expert Licensed User

    What is your question? Why wouldnt it be possible?
     
  10. espi

    espi Member Licensed User

    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,,

    Code:
    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
     
  11. Erel

    Erel Administrator Staff Member Licensed User

    You are confusing Java with JavaScript. There is no 'alert' method in Java.
     
    thedesolatesoul likes this.
  12. Devv

    Devv Active Member Licensed User

    Time to learn JAVA :D
    thanks Erel you are a hard worker :cool:
     
  13. wonder

    wonder Well-Known Member Licensed 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?
     
  14. thedesolatesoul

    thedesolatesoul Expert Licensed User

    Not the J2ME and other platform specific portions. You can call pura java functions though.
     
    lemonisdead, NJDude and wonder like this.
  15. corwin42

    corwin42 Expert Licensed User

    Great feature.

    Just added these lines to a sample project:
    Code:
    #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(101"Plus one", xml.GetDrawable("ic_plus_one_black_24dp")).ShowAsAction = item.SHOW_AS_ACTION_ALWAYS
        
    Menu.Add2(202"Refresh", xml.GetDrawable("ic_refresh_black_24dp")).ShowAsAction = item.SHOW_AS_ACTION_ALWAYS

        
    Menu.Add(13"Overflow1"Null)
        
    Menu.Add(24"Overflow2"Null)
        
    Menu.Add(35"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.
     
    Theera, DonManfred, johndb and 5 others like this.
  16. espi

    espi Member Licensed User

    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

    Code:
    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
     
  17. Erel

    Erel Administrator Staff Member Licensed User

    javax.swing API is not included in Android SDK.
     
    Johan Schoeman likes this.
  18. espi

    espi Member Licensed User

    Hi Erel,

    cheers

    ok i have understand principal.
    Great work!

    greetings
    espi


    Code:
    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
     
  19. Spinter

    Spinter Active Member Licensed User

    For example how can I pass two string data?
     
  20. stevel05

    stevel05 Expert Licensed User

    Code:
    NativeMe.Runmethod("methodName",Array("String1","String2"))
     
Loading...