2012-08-13 81 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

相关问题