views:

750

answers:

3

I believe that it's possible to call Java methods from (PhoneGap) Javascript.

Anyone knows how to do that?? (I know how to do it by changing the source code of PhoneGap, but I'd avoid that)

+1  A: 

You have to change the source code to PhoneGap. Otherwise, you are limited to the APIs PhoneGap publishes.

CommonsWare
You are absolutely sure about this? I've found this for iPhone: http://groups.google.com/group/phonegap/browse_thread/thread/82205d4a4d561b38/d1b81b691b185e17 so i hoped something like that is doable in Java too...
zorglub76
My read of the PhoneGap Android source says they took a different approach and do not have the equivalent of `PhoneGapCommand`. However, PhoneGap knows more about PhoneGap than I do, so would recommend you ask your question on that Google Group and see what they say.
CommonsWare
already did, but no one answered :(
zorglub76
+2  A: 

I finally made it work.

  • Create a class with methods you want to use:
public class MyClass {
    private WebView mAppView;
    private DroidGap mGap;

    public MyClass(DroidGap gap, WebView view)
    {
        mAppView = view;
        mGap = gap;
    }

    public String getTelephoneNumber(){
        TelephonyManager tm = (TelephonyManager) mGap.getSystemService(Context.TELEPHONY_SERVICE);
        String number = tm.getLine1Number();
        return number;
    }
}
  • In your main activity add a Javascript interface for this class:
public class Main extends DroidGap
{
    private MyClass mc;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        mc = new MyClass(this, appView);
        appView.addJavascriptInterface(mc, "MyCls");

        super.loadUrl(getString(R.string.url));
    }
}
  • In Javascript call window.MyCls methods:

    $(function(){
        $("#phone").text("My telephone number is: " + 
                window.MyCls.getTelephoneNumber());
    });


zorglub76
A: 

Excelent!, very usefull.

But, is there a way you can call JavaScript functions from Java?

Andres Canabal
You should post follow-up question as a separate thread, notas an answer. After all, it doesn't really answer *this*question. Also more people would see it and try to answer if you post it asyour own question.
sth
Yes, you can (I mean "you can call js", not "you can post follow-up questions"). In Java add something like this: appView.loadUrl("javascript:myJsFunction('" + myJavaVariable + "')"); Of course, you have to create "myJsFunction()" where your javascript code is. Anyway, this is not PhoneGap's invention. You can do everything described above in pure Android...
zorglub76