当前位置:  开发笔记 > 编程语言 > 正文

Android Java和Phonegap Javascript之间的通信?

如何解决《AndroidJava和PhonegapJavascript之间的通信?》经验,为你挑选了5个好方法。

我相信可以从(PhoneGap)Javascript调用Java方法.

谁知道怎么做?(我知道如何通过更改PhoneGap的源代码来实现,但我会避免这种情况)



1> zorglub76..:

我终于成功了.

使用您要使用的方法创建一个类:

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;
  }
}

在您的主要活动中为此类添加Javascript接口:

public class Main extends DroidGap
{
    private MyClass mc;

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

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

        super.loadUrl(getString(R.string.url));
    }
}

在Javascript调用window.MyCls方法:


注意:

如评论中所述,对于Android 4.2及更高版本,请添加@JavascriptInterface要从HTML页面访问的方法.参考.


很好!提示:如果你想以相反的方式进行通信(从Java到Javascript),请使用:mGap.sendJavascript("window.myJavascriptFunction('some parameter');");
E/Web控制台(2513):未捕获的TypeError:对象[object Object]在file:///android_asset/www/loginfile.js:142 window.Mycls.sendEmail("rea@gmail.com")中没有方法'sendEmail' ); 在此行获取错误
我已经尝试了Android 4.2.2的这个代码,我遇到了类似于Deepu的问题,即Uncaught TypeError:Object [object Object]在file:///android_asset/www/app.js:142中没有方法'getTelephoneNumber'.经过一些调试后,我发现你需要添加@JavascriptInterface来访问你想要在4.2.2以上的javascript中访问的任何方法[link](http://stackoverflow.com/questions/14031635/android-4-2-1 -webview和JavaScript的接口,休息时间)

2> 小智..:

addJavaScriptInterface(mc, "MyCls")没有Gap init()ed可能会导致应用程序崩溃,你最好super.init()先添加addJavascriptInterface()

public class Main extends DroidGap
{
   private MyClass mc;

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

       super.init();

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

       super.loadUrl(getString(R.string.url));
   }
}



3> Chui Tey..:

PhoneGap有一个不错的插件API.您可以通过实现IPlugin接口在Java中编写插件.大多数魔法都在execute()函数中.

public interface IPlugin {

    /**
     * Executes the request and returns PluginResult.
     *
     * @param action        The action to execute.
     * @param args          JSONArry of arguments for the plugin.
     * @param callbackId    The callback id used when calling back into JavaScript.
     * @return              A PluginResult object with a status and message.
     */
    PluginResult execute(String action, JSONArray args, String callbackId);

        // ... more ...
}

开始编写插件的最佳方法是首先编写javascript API.你通常会先编写一个自定义的javascript类,然后在javascript类的每个方法中,编组变量并调用你使用Phonegap.exec()方法开发的插件.以下是方法签名供您参考.

/* src/com/phonegap/api/PluginManager.java */
/**
 * Receives a request for execution and fulfills it by finding the appropriate
 * Java class and calling it's execute method.
 *
 * PluginManager.exec can be used either synchronously or async. In either case, a JSON encoded
 * string is returned that will indicate if any errors have occurred when trying to find
 * or execute the class denoted by the clazz argument.
 *
 * @param service       String containing the service to run
 * @param action        String containt the action that the class is supposed to perform. This is
 *                      passed to the plugin execute method and it is up to the plugin developer
 *                      how to deal with it.
 * @param callbackId    String containing the id of the callback that is execute in JavaScript if
 *                      this is an async plugin call.
 * @param args          An Array literal string containing any arguments needed in the
 *                      plugin execute method.
 * @param async         Boolean indicating whether the calling JavaScript code is expecting an
 *                      immediate return value. If true, either PhoneGap.callbackSuccess(...) or
 *                      PhoneGap.callbackError(...) is called once the plugin code has executed.
 *
 * @return              JSON encoded string with a response message and status.
 */
@SuppressWarnings("unchecked")
public String exec(final String service, final String action,
    final String callbackId, final String jsonArgs,
    final boolean async)

您还需要注册插件.您可以通过在自定义JavaScript库底部添加注册码来完成此操作.

在下面的示例中,作者定义了一个javascript BarcodeScanner类,并使用addConstructor方法对其进行注册.

在addConstructor中执行两个步骤:

    在javascript中创建一个新的BarcodeScanner实例并注册它.这可以通过javascript作为window.plugins.barcodeScanner访问

    使用服务名称注册自定义Plugin类.此服务名称作为PhoneGap.exec的第一个参数传入,以便PhoneGap可以实例化java插件类并在其上调用execute()方法.

样品注册码:

PhoneGap.addConstructor(function() {
    /* The following registers an instance of BarcodeScanner in window.plugins.barcodeScanner */
    PhoneGap.addPlugin('barcodeScanner', new BarcodeScanner());

    /* The following associates a service name BarcodeScanner with a class com.beetight.barcodescanner.BarcodeScanner */
    /* The service name is the first argument passed into PhoneGap.exec */
    PluginManager.addService("BarcodeScanner","com.beetight.barcodescanner.BarcodeScanner");
});



4> 小智..:

一个更简单的形式:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.init(); 
    super.appView.getSettings().setJavaScriptEnabled(true);
    super.appView.addJavascriptInterface(this, "MyCls");
    super.loadUrl("file:///android_asset/www/login.html");
}



5> Dhairya Vora..:

如果有人使用上面的代码获取nullPointer异常,先执行super.oncreate(),然后执行super..init()

super.onCreate(savedInstanceState);
super.init();

我在这里找到了这个解决方案:Phonegap Google Group

非常感谢@ zorglub76的解决方案....

推荐阅读
360691894_8a5c48
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有