我使用新的 api 来获取位置。但即使有了这个新的 api,我的设备也会使位置过时。此方法 (getLastLocation()) 获取的位置已过期。如果 wifi 正常,它会获得实际位置。但是当wifi关闭时,它会得到一个旧位置。谷歌的地图应用程序是如何快速获取位置的?
这是我正在使用的课程:
public class NewGPSTracker implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener, com.google.android.gms.location.LocationListener {
private LocationRequest lr;
private LocationClient lc;
Location location;
double latitude = 0;
double longitude = 0;
Context context;
public int res = 0;
boolean connected;
public NewGPSTracker(Context context) {
this.context = context;
lr = LocationRequest.create();
lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
lr.setInterval(5000);
lr.setFastestInterval(1000);
lc = new LocationClient(context, this, this);
sp = context.getSharedPreferences("GPS", 0);
editor = sp.edit();
}
@Override
public void onLocationChanged(Location location) {
if (connected && location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
@Override
public void onConnected(Bundle connectionHint) {
Log.i("NewGPSTracker", "Google Play Services Conectado.");
lc.requestLocationUpdates(lr, this);
connected = true;
location = lc.getLastLocation();
if (connected && location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.i("Location", ""+latitude + " "+longitude);
}
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
Log.e("NewGPSTracker", ""+arg0);
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public void connect(){
lc.connect();
}
public void disconnect(){
lc.disconnect();
}
@Override
public void onDisconnected() {
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}