我正在开发一个 Android 应用程序,我需要确保设备已达到用纬度和经度描述的某个点。我唯一能想到的就是拥有这样的东西:
Location initLoc = theManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double lat = initLoc.getLatitude();
double lon = initLoc.getLongitude();
MyPoint firstPoint = getPoints().get(0);
double dist = CalcHelper.getDistance1(lat, lat, firstPoint.getLat(), firstPoint.getLon());
while(dist > 30){
initLoc = theManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lat = initLoc.getLatitude();
lon = initLoc.getLongitude();
dist = CalcHelper.getDistance1(lat, lon, firstPoint.getLat(), firstPoint.getLon());
}
但这会导致程序崩溃。如果您能引导我走向正确的方向,我将非常感激。
让我借此机会再问一个问题。正如我所说,我是 Android 和 GPS 的新手,并且考虑到几乎没有关于如何正确开发与 GPS 配合使用的应用程序的文档和信息,我基本上是在盲目工作。所以我的问题是:
这是 onLocationChanged 方法的样子:
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
MyPoint firstPoint = MainScreen.dataset.getPoints().get(0);
double dist = CalcHelper.getDistance1(lat, firstPoint.getLat(),lon, firstPoint.getLon());
if(dist < 10){
Context context = getApplicationContext();
CharSequence text = "Start reached. Starting moving on track";
int duration = 6000;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}else{
Context context = getApplicationContext();
CharSequence text = "Distance until start: "+dist;
int duration = 6000;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
我想做的是让程序确定我何时到达我作为一组点提供的轨道的起点。因此,当我启动该程序时,我会收到对距离的合理估计。问题是,当我开始移动时,距离似乎没有更新,它会更新,但移动 50 米后,它说我只移动了 5 米。另一方面,当我启动应用程序并且距离起点不到 10m 时,它会正确检测到它。所以基本上,当我带着设备移动时, onLocationChanged 方法似乎没有给我现在所在的正确位置。你能告诉我我可能做错了什么吗?
最佳答案
我认为你想要做的是让你的 Activity 实现 LocationListener,即订阅 GPS 修复。例如。
public class MyActivity extends Activity implements LocationListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// request current location updates
LocationManager locMan = (LocationManager) getSystemService(LOCATION_SERVICE);
// set here the criteria for location provider accuracy
Criteria locationProviderCriteria = new Criteria();
locationProviderCriteria.setAccuracy(Criteria.ACCURACY_FINE);
String locationProvider = locMan.getBestProvider(locationProviderCriteria, true);
locMan.requestLocationUpdates(locationProvider, MIN_TIME_BETWEEN_UPDATES_IN_MILLIS, MIN_DISTANCE_BETWEEN_UPDATES_IN_METERS, this);
}
/*
* This method will be called on each location update
*/
@Override
public void onLocationChanged(Location loc) {
//put here your logic to see whether the user reached the destination
}
}
关于安卓 GPS : how to check if a certain point has been reached?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5266486/