【发布时间】:2018-12-04 14:01:51
【问题描述】:
我想要做的是每次调用函数时获取位置纬度和经度。据我所知,最好的方法是将位置更新保留几秒钟以获取正确的修复,然后将其禁用,但我无法使其在我的应用中运行。
到目前为止,我所做的是在每次调用 displayData 函数时获取手机的最后一个已知位置,但我无法克服尝试更改为时出现的所有错误请求位置更新。我在这里所做的是调用 displayData 函数,当有来自蓝牙设备的传入数据时,以获取位置并将数据+位置写入文件。
谁能帮助我,因为所有指南都显示了如何在位置更新时触发某些东西,但我不想这样做。 我只是想要一个定期的正确位置...
private void displayData(final byte[] byteArray) {
try {
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 (byteArray != null) {
String data = new String(byteArray);
tv.setText(n/2 + " measurements since startup...");
n += 1;
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latitude = String.valueOf(lat);
longitude = String.valueOf(lng);
}
try
{
FileWriter fw = new FileWriter(textfile,true); //the true will append the new data
if (writeDate()) {
fw.write("\n");
fw.write(stringDate);
fw.write(data); //appends the string to the file
}
else {
fw.write(data); //appends the string to the file
fw.write(" - ");
fw.write(latitude);
fw.write(",");
fw.write(longitude);
}
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
// find the amount we need to scroll. This works by
// asking the TextView's internal layout for the position
// of the final line and then subtracting the TextView's height
final int scrollAmount = tv.getLayout().getLineTop(
tv.getLineCount())
- tv.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
tv.scrollTo(0, scrollAmount);
else
tv.scrollTo(0, 0);
}
}
});
} catch (SecurityException e) {
// lets the user know there is a problem with the gps
}
}
【问题讨论】:
-
也许您可以将获取/维护位置和调用
displayData()解耦。只需为最新位置设置一个变量并在displayData()中使用它。然后担心根据绝对需要的准确度以及设备应该移动的速度分别维护最新的位置。如果速度很高并且位置需要准确,您可能只需请求位置更新并保持它们的出现。否则,您可以通过请求更新、接收一个或几个然后取消它们以节省电池来定期更新。 -
这可能是合理的,因为获取位置是异步的,而您的
displayData()显然应该是同步的,而不是等待其他一些操作完成。但您更了解自己的应用。 -
谢谢马库斯。我也喜欢你的方法。如果我想节省电池,我可以设置一个等于 displayData 重复周期的 minTime 值(更新位置),我会没事的,不是吗?如果我在 displayData “外部”获取更新的位置,我什至可以保留此代码并使用最后一个非常准确的已知位置,对吧?
-
是的,“最后一个已知位置”将与
onLocationChanged()回调返回的最新位置一样好(相同)。从理论上讲,如果其他一些应用程序也请求位置更新,它可能会有所不同。甚至可能使用“更糟糕”的设置。存储在onLocationChanged()中收到的值可能是一种更安全的方式。我还没有实际测试过这种情况。
标签: java android geolocation