我们已经构建了一个目前在沙特阿拉伯使用的 Android 应用程序,我们在用户点击特定按钮时获取用户的位置。
我们使用 Google Location API 获取位置直到 5 秒,根据我们的要求,我们需要获得小于 50 的准确度。
在某些情况下,我们获得了这种准确度,但在某些情况下,我们获得了超过 100 到 2000 的准确度。
我们使用以下代码构建了此功能。
public class LocationService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private LocationRequest locationRequest;
private GoogleApiClient locationClient;
private Context tempContext = null;
public static Location mLastLocation = null;
public Handler mHandler = null;
long Id = 0;
public LocationService(Context context) {
try {
tempContext = context;
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(tempContext) == ConnectionResult.SUCCESS) {
locationRequest = LocationRequest.create();
locationRequest.setInterval(ConstantData.ACTION_LOCATIONTIME_INTERVAL); // 2000
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationClient = new GoogleApiClient.Builder(tempContext)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
if (!locationClient.isConnected() || !locationClient.isConnecting()) {
locationClient.connect();
}
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setNeedBle(true);
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
try {
mLastLocation = getLocation();
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi
.requestLocationUpdates(locationClient, locationRequest, this);
getLocation task = new getLocation();
task.execute((Void) null);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Location getLocation() {
return LocationServices.FusedLocationApi
.getLastLocation(locationClient);
}
public void stopLocationUpdates() {
try {
if (locationClient != null && locationClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(locationClient, this);
locationClient.disconnect();
locationClient = null;
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class getLocation extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
int limit = 0, totaltry = 0;
try
{
totaltry = 10;
while (limit < totaltry) {
Thread.sleep(500);
mLastLocation = getLocation();
if (mLastLocation != null
&& mLastLocation.getAccuracy() < 50)
break;
limit++;
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
try
{
stopLocationUpdates();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
目前,我们正在尝试使用以下链接作为参考来实现相同的功能。
http://adavis.info/2014/09/android-location-updates-with-the-fusedlocationapi.html