2012-08-13 55 views
1

我想將加速度值從js傳遞給java。誰能告訴我哪裏錯了?如何將JS代碼中的值傳遞給Java中的JSNI

這裏是我的代碼:

public class Accelerometer extends JavaScriptObject { 

protected Accelerometer(){}; 

public static native double getCurrentAccelerationX() /*-{ 
    var x = 0.0; 
    $wnd.ondevicemotion = function(event){ 
    //$wnd.alert(event.accelerationIncludingGravity.x); 
    x = event.accelerationIncludingGravity.y; 
    }; 
    return x; 
}-*/; 

}

+0

看到[這篇文章](http://stackoverflow.com/questions/9584991/how-to-instantiate-a-java-class-from-within-jsni)。 – 2012-08-15 09:44:26

回答

0

好了,你有什麼不會起作用,因爲你的函數立即返回,但實際值不可用,直到稍後的時間。

當你的類發生變化時,你需要讓你的JSNI函數調用一個方法。

(另外:如果你已經張貼什麼是您的Accelerometer類的程度,就沒有必要讓它擴展JavaScriptObject。)

嘗試是這樣的:

package foo.bar; 

public class Accelerometer { 
    public void currentAcceleration(double x, double y) { 
     Window.alert("currentAcceleration: " + x + ", " + y); 
    } 

    public static native void getCurrentAcceleration(Accelerometer p) /*-{ 
     $wnd.ondevicemotion = function(event) { 
      var acc = event.accelerationIncludingGravity; 
      $entry([email protected]::currentAcceleration(DD)(acc.x, acc.y)); 
     }; 
    }-*/; 
} 

你可以使此方法成爲Accelerometer的成員而不是靜態方法,但我更願意將該實例作爲參數傳遞給該函數,以避免與this混淆。

+0

非常感謝!這正是我需要的! – user1486355 2012-08-16 19:15:12

+0

隨時upvote /接受 – funkybro 2012-08-17 07:00:36

相關問題