我有以下LocationService.java
服務類。獲取不正確的當前GPS位置在FusedLocationProviderApi
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)
它是設備特定問題?或者我需要改變我的代碼? 我該怎麼做才能使我的位置服務更好?
你爲什麼不使用常規的位置提供被動? 像GPS或網絡提供商 –
@Haidar我用GPSTracker.java類用於獲取當前位置,但我覺得這不是頻繁地更新當前位置的位置...所以我用它。 – himCream