【发布时间】:2013-10-16 03:38:48
【问题描述】:
我有一个简单的类 GPSListener 获取 GPS 坐标:
public class GPSListener implements LocationListener {
public static double latitude;
public static double longitude;
@Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.d("GPSLISTENER ", "lat: "+latitude+" long:"+longitude);
} ...
然后尝试在我的活动中使用这个类,我只需在我的活动中的onCreate() 函数中调用该类:
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new GPSListener();
Criteria criteria = new Criteria();
String bestProvider = mlocManager.getBestProvider(criteria, false);
mlocManager.requestLocationUpdates(bestProvider, 0, 0, mlocListener);
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
lat = GPSListener.latitude;
lon = GPSListener.longitude;
Log.d("GPS", "lat: "+lat+" long:"+lon);
} else {
// TODO: GPS not enabled
Log.d("GPSERROR", "GPS not enabled");
}
但是每当我运行应用程序时,我的活动中的lat 和lon 总是为零。我不太确定如何解决这个问题。
记录时:
Log.d("GPSLISTENER ", "lat: "+latitude+" long:"+longitude);
它返回正确的纬度和经度,活动开始后只需一两秒。
Log.d("GPSSUCCESS", "lat: "+lat+" long:"+lon);
两者都返回 0.0。我的印象是.requestLocationUpdates 会在执行 if 语句之前将值传递给lat 和lon。我怎样才能做到这一点?
【问题讨论】:
-
您是否在清单文件中添加了位置权限(android.permission.ACCESS_FINE_LOCATION)?
-
如果您在模拟器上进行测试,您需要将坐标传递给它,或者如果您在您的设备上,请重新启动设备并检查。
-
@Shrikant 我正在我的设备上进行测试。正如我所说,它能够在 GPSListener 中获取 GPS 坐标,所以我认为这不是通信错误。我认为这更有可能是语法错误。