使用FusedLocationProviderClient获取按钮单击时的最后一个已知位置

时间:2017-09-14 12:23:27

标签: java android geolocation

我需要通过点击按钮立即将当前位置返回到服务器。

mFusedLocationClient.getLastLocation()
        .addOnSuccessListener(this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                // Got last known location. In some rare situations this can be null.
                if (location != null) {
                    // ...
                }
            }
        });

在Android文档中,建议使用这种方式来获取位置。但正如你所看到的那样,它并没有立即返回。在thread.sleep()运行之前,我应该等待onSuccess或相关的事情吗?或者最好的方法是什么?

2 个答案:

答案 0 :(得分:0)

调用成功后,调用一些方法将位置上传到服务器。

mFusedLocationClient.getLastLocation()
        .addOnSuccessListener(this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                // Got last known location. In some rare situations this can be null.
                if (location != null) {
                    sendToServer();
                }
            }
        });

答案 1 :(得分:0)

没有办法立即获得该位置&#34;&#34;。你必须等待回调。不,不要使用任何睡眠方法。在UI线程上,它会阻止ui,甚至不需要。只需通过onSuccess将位置发送到您的服务器。