这是我连接 locationClient 后调用的 onConnected() 方法。此方法称为 ok,因此 GPS 连接正常。但是,getLastLocation() 返回 null,这可能是由于尝试过早地获取位置而可以预期的,并且根本没有调用 locationListener 方法。它在三星 Galaxy S3 上运行。当我打开谷歌地图应用程序时,它会立即确定我的位置,所以 GPS 一定没问题。
@Override
public void onConnected(Bundle arg0)
{
Toast.makeText(context, "GPS connected", Toast.LENGTH_SHORT).show();
connector = new Connector();
connector.execute("clues", null, null);
listener = new LocationListener()
{
@Override
public void onLocationChanged(Location location)
{
Log.d("location", "listener activated");
try
{
coords = locationCoords(location);
if(coords[0] != 0)
{
meMarker = map.addMarker(new MarkerOptions()
.position(new LatLng(coords[0], coords[1]))
.title("Me")
.snippet("Your position")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(coords[0], coords[1]), (float) 19));
}
Toast.makeText(context, coords[0] + ", " + coords[1], Toast.LENGTH_LONG).show();
}
catch(NullPointerException e)
{
Log.d("nulls", "null");
}
}
};
mLocationClient.requestLocationUpdates(mLocationRequest, listener);
try
{
coords = locationCoords(new Location(mLocationClient.getLastLocation()));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(coords[0], coords[1]), (float) 19));
}
catch(NullPointerException e)
{
Toast.makeText(context,"location null", Toast.LENGTH_LONG).show();
}
//Toast.makeText(context, coords[0] + ", " + coords[1], Toast.LENGTH_LONG).show();
Log.d("location", "location updates initiated");
}
定义请求参数:
public dbConnector(Context con, Activity acti, GoogleMap map)
{
context = con;
activity = acti;
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
setGPSUpdates(10000, 5000);
mLocationRequest.setInterval(updateRate);
mLocationRequest.setFastestInterval(fastestUpdate);
mLocationRequest.setSmallestDisplacement(1);
Log.d("location", "location request constructed");
this.map = map;
}
public void setGPSUpdates(int update, int fastupdate)
{
updateRate = update;
fastestUpdate = fastupdate;
}