我尝试了以下代码,它正在运行,但是在启动应用程序后首次单击按钮,单击按钮时坐标显示正确的消息,但是对于下次单击,消息很长时间不幸显示消息。
我的代码如下:
button.setOnAction(e->{
PositionService positionService = Services.get(PositionService.class).orElseThrow(() -> new RuntimeException("PositionService not available."));
positionService.positionProperty().addListener((obs, ov, nv) -> MobileApplication.getInstance().showMessage("Latest known GPS coordinates from device: " + nv.getLatitude() + ", " + nv.getLongitude()));
});
提前致谢。
答案 0 :(得分:1)
假设您有一个使用您的IDE的Gluon插件创建的单个视图项目,并且您已将所需的location
服务和权限添加到Android清单中:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
例如,您可以在BasicView
中执行:
public BasicView(String name) {
super(name);
Label label = new Label("GPS is not active");
Button button = new Button("Active GPS");
button.setGraphic(new Icon(MaterialDesignIcon.LOCATION_ON));
button.setOnAction(e -> {
Services.get(PositionService.class).ifPresent(service -> {
// if there is GPS service, disable button to avoid adding more
// listeners
button.setDisable(true);
label.setText("Waiting for GPS signal");
service.positionProperty().addListener((obs, ov, nv) ->
label.setText("Latest known GPS coordinates:\n" + nv.getLatitude() + ", " + nv.getLongitude()));
});
});
VBox controls = new VBox(15.0, label, button);
controls.setAlignment(Pos.CENTER);
setCenter(controls);
}
或者您可以在创建视图时初始化服务,而无需激活它:
public BasicView(String name) {
super(name);
Label label = new Label("GPS is not active");
Services.get(PositionService.class).ifPresent(service -> {
label.setText("Waiting for GPS signal");
service.positionProperty().addListener((obs, ov, nv) ->
label.setText("Latest known GPS coordinates:\n" + nv.getLatitude() + ", " + nv.getLongitude()));
});
}
无论哪种方式,您都可以将应用部署到Android / iOS设备并进行测试。
修改强>
或者,如果您想要包含一个按钮,那么您可以根据需要随时点击它。
public BasicView(String name) {
super(name);
Label label = new Label("GPS is not active");
Button button = new Button("Get GPS coordinates");
button.setGraphic(new Icon(MaterialDesignIcon.LOCATION_ON));
button.setDisable(true);
Services.get(PositionService.class).ifPresent(service -> {
label.setText("Waiting for GPS signal");
service.positionProperty().addListener((obs, ov, nv) -> {
label.setText("Latest known GPS coordinates:\n" + nv.getLatitude() + ", " + nv.getLongitude());
});
// enable button and add listener to retrieve coordinates
button.setDisable(false);
button.setOnAction(e -> {
Position position = service.getPosition();
MobileApplication.getInstance().showMessage("Latest known GPS coordinates from device:\n" +
position.getLatitude() + ", " + position.getLongitude());
});
});
VBox controls = new VBox(15.0, label, button);
controls.setAlignment(Pos.CENTER);
setCenter(controls);
}
请注意,点击该按钮时,您应使用service.getPosition()
。