【发布时间】:2015-11-30 11:07:50
【问题描述】:
我正在开发 GpsTracker 应用程序,目前正在使用 gps 获取 lat,lng 值,一旦我关闭 gps,我无法获得任何 lat,lng 值,但我的要求是移动数据或 wifi 或 gps,具体取决于我需要的可用性为了获得 lat,lng 值,我非常了解使用位置管理器,但与 googleapi 客户端相比,它消耗更多电池,所以我使用了 googleapi 客户端 - fusedlocationproviderapi 请指导我为什么它在当前 api 中无法使用此功能。
public class UpdateLocation extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleApiClient mLocationClient;
private Location mCurrentLocation;
LocationRequest mLocationRequest;
private static final String TAG = "UpdateLocationService";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO do something useful
Toast.makeText(this, "onStartCommand", Toast.LENGTH_SHORT).show();
createLocationRequest();
mLocationClient = new GoogleApiClient.Builder(UpdateLocation.this)
.addApi(LocationServices.API).addConnectionCallbacks(UpdateLocation.this)
.addOnConnectionFailedListener(UpdateLocation.this).build();
mLocationClient.connect();
return Service.START_STICKY;
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
mCurrentLocation = location;
Toast.makeText(this, mCurrentLocation.getLatitude() +", "+ mCurrentLocation.getLatitude(), Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "Connection failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
if (mLocationClient.isConnected()) {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mLocationClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
if (mLocationClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(
mLocationClient, this);
}
mLocationClient.disconnect();
}
}
【问题讨论】:
-
位置管理器何时弃用?我听说只有 LocationClient 已被弃用。
-
当你关闭gps时,你是否将定位模式设置为关闭?您需要将定位模式设置为省电模式才能仅测试网络定位。
-
@MadhukarHebbar 是的,你是对的......:谢谢
-
是否可以使用 wifi/移动数据的 google api 客户端获取 lat 和 lng 值?@MadhukarHebbar
-
@balaji 我认为你不应该完全关闭 GPS;如果您正在请求位置更新,那么您需要致电
LocationServices.FusedLocationApi.getLastLocation( mGoogleApiClient);以便从提供商处获取最后一个已知位置。
标签: android latitude-longitude