Gwt 如何在JSNI中将值从JS代码传递到Java

Gwt 如何在JSNI中将值从JS代码传递到Java,gwt,jsni,Gwt,Jsni,我想把加速度值从js传递到java。谁能告诉我哪里不对吗 这是我的密码: public class Accelerometer extends JavaScriptObject { protected Accelerometer(){}; public static native double getCurrentAccelerationX() /*-{ var x = 0.0; $wnd.ondevicemotion = function(event){ //$wn

我想把加速度值从js传递到java。谁能告诉我哪里不对吗

这是我的密码:

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

}

好的,因为函数立即返回,所以您所拥有的不会起作用,但实际值在以后才可用

当类发生更改时,需要让JSNI函数调用类中的方法

另外:如果您发布的是加速计类的范围,则无需使其扩展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( p.@foo.bar.Accelerometer::currentAcceleration(DD)(acc.x, acc.y) );
        };
    }-*/;
}

您可以将此方法设置为加速计的成员,而不是静态的,但我更喜欢将实例作为参数传递给函数,以避免与此混淆。

请参阅。非常感谢!这正是我需要的!