2011-08-17 94 views
0

我正在開發一個項目,關於在WebView演示之後在android上嵌入web應用程序,但是當javascript函數'wave'時需要調用gwt函數由Android應用程序回叫:如何在調用javascript函數時調用gwt函數

<html> 
    <script language="javascript"> 
     /* This function is invoked by the activity */ 
     function wave(s) { 
       // call a gwt function and 
       // pass 's' to the gwt function 
     } 
    </script> 
    <body> 
     <!-- Calls into the javascript interface for the activity --> 
     <a onClick="window.demo.clickOnAndroid()"><div style="width:80px; 
      ... 
     </div></a> 
    </body> 
</html> 

有關如何實現此目的的任何想法?

回答

5

您將需要將您想調用的任何方法從javascript導出到javascript全局範圍中。這意味着你不能從手寫javascript調用任意的java方法。您必須提前計劃並在javascript範圍內公開必要的方法。

過程是非常簡單的:

  1. 編寫創建於$ WND範圍功能的JSNI方法。
  2. 從這個函數的主體調用java方法使用JSNI JavaScript to java syntax
  3. 在應用程序啓動期間調用步驟#1中聲明的方法(例如,從入門點onmoduleload)
  4. 調用在$ wnd作用域中創建的函數從您的javascript。確保在加載gwt模塊並運行入口點後執行此操作。

GWT JSNI documentation與附加註釋的例子:

package mypackage; 

public MyUtilityClass 
{ 
    //Method to be called from javascript, could be in any other class too 
    public static int computeLoanInterest(int amt, float interestRate, 
              int term) { ... } 
    //This method should be called during application startup 
    public static native void exportStaticMethod() /*-{ 
     //the function named here will become available in javascript scope 
     $wnd.computeLoanInterest = 
      $entry(@mypackage.MyUtilityClass::computeLoanInterest(IFI)); 
    }-*/; 
} 

編輯:

將參數傳遞給Java方法:

當你調用Java方法需要參數ERS,從JavaScript,你需要使用一個特定的語法:

[instance-expr.]@class-name::method-name(param-signature)(arguments) 

例如,調用,需要一個字符串參數的靜態方法是這樣的:

@com.google.gwt.examples.JSNIExample::staticFoo(Ljava/lang/String;)(s); 

需要注意的是,我們在呼喚一個靜態方法,'實例表達式'。被省略。其餘代碼是完全合格的類名稱,後跟::和方法名稱。方法名稱後面的Ljava/lang/String;指定我們需要調用以String對象爲參數的方法。最後s是該參數的實際值。

請記住,在我們的例子中,參數簽名Ljava/lang/String;在語法上使用JNI type signature specs,並且GWT編譯器要求選擇正確的方法,即使存在多個具有相同名稱的重載方法。即使方法沒有過載,也需要param-signature

+0

我的gwt應用程序現在可以接收來自硬寫javascript的事件,但這是空參數。我需要將String傳遞給gwt函數作爲它的參數,但是我不能在@entry中做到這一點,關於如何實現這一點的任何想法? – xybrek

+0

@xybrek查看更新的答案 –

1

GWT被編譯爲javascript,並且所有函數/對象名都被縮小了,所以它們變得不可讀和未知,所以你不能直接從Javascript調用它們。要解決這個問題,你需要檢查如何Call a Java Method from Handwritten JavaScript