我有以下的LocationService.java服务类。
在上述位置服务中,我所做的是: 1. 将最快的刷新间隔设置为每5秒钟更新一次位置。 2. 一旦位置可用,就会触发
我已在清单文件中提到了两个位置条件,如下所示:
public class LocationService extends Service
implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final long INTERVAL = 1000 * 60;
private static final long FASTEST_INTERVAL = 1000 * 5;
Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
String lat, lon;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mGoogleApiClient.connect();
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = String.valueOf(mLastLocation.getLatitude());
lon = String.valueOf(mLastLocation.getLongitude());
Util.WriteSharePrefrence(getApplicationContext(), "track_lat", "" + lat);
Util.WriteSharePrefrence(getApplicationContext(), "track_lng", "" + lon);
}
}
@Override
public void onCreate() {
int permissionCheck = ContextCompat.checkSelfPermission(LocationService.this, Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
//Execute location service call if user has explicitly granted ACCESS_FINE_LOCATION..
buildGoogleApiClient();
}
}
@Override
public void onConnectionSuspended(int i) {
}
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
Util.WriteSharePrefrence(getApplicationContext(), "track_lat", "" + location.getLatitude());
Util.WriteSharePrefrence(getApplicationContext(), "track_lng", "" + location.getLongitude());
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
buildGoogleApiClient();
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
在上述位置服务中,我所做的是: 1. 将最快的刷新间隔设置为每5秒钟更新一次位置。 2. 一旦位置可用,就会触发
onLocationChanged()
。在 onLocationChanged()
方法中,我将当前的纬度和经度写入共享偏好中。
3. 此服务将在后台运行24小时以获取当前位置。我已在清单文件中提到了两个位置条件,如下所示:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
我的问题是:
有时onLocationChanged()
方法会取到错误的纬度和经度,例如:用户设备在印度,但它获取到了美国的地址。设备版本为Xolo - 4.2.1.(India)
这是设备特定的问题吗?还是我需要更改代码?我应该怎么做才能让我的定位服务更好?