2017-01-02 2 views
1

Я создаю приложение, которое устанавливает текущее местоположение пользователей (A), а затем пользователь нажимает кнопку, чтобы установить новое текущее местоположение пользователя (B), а затем я рисую путь между этими двумя точками. У меня есть служба, которая получает местоположение, используя Fused Locations. Проблема заключается в том, что большую часть времени я получаю локаций с hasAccuracy = ложь и getAccuracy> 20.Как улучшить точность местоположения в моем приложении для Android-приложений?

Вот моя служба:

import android.app.Service; 
import android.content.Intent; 
import android.location.Location; 
import android.os.Binder; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.IBinder; 
import android.util.Log; 
import android.widget.Toast; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GooglePlayServicesUtil; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.location.LocationServices; 

public class GoogleMapService extends Service implements LocationListener { 

    private static final String TAG = "GoogleMapServiceTAG_"; 
    private IBinder myBinder = new GoogleMapServiceBinder(); 

    // Google client to interact with Google API 
    private GoogleApiClient mGoogleApiClient; 

    private LocationRequest mLocationRequest; 

    private double fusedLatitude = 0.0; 
    private double fusedLongitude = 0.0; 

    private static final long INTERVAL = 1000 * 5; 
    private static final long FASTEST_INTERVAL = 1000 * 3; 

    public void init() { 
     if (checkPlayServices()) { 
      startFusedLocation(); 
      startLocationUpdates(this); 
     } 
    } 

    public void startLocationUpdates(final LocationListener listener) { 

     new Handler().postDelayed(new Runnable() { 
      @Override 
      public void run() { 
       // TODO Auto-generated method stub 
       try { 
        LocationServices.FusedLocationApi. 
          requestLocationUpdates(mGoogleApiClient, mLocationRequest, listener); 
       } catch (SecurityException e) { 
        e.printStackTrace(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
        if (!isGoogleApiClientConnected()) { 
         mGoogleApiClient.connect(); 
        } 
        startLocationUpdates(listener); 
       } 
      } 
     }, 1000); 
    } 

    public boolean isGoogleApiClientConnected() { 
     return mGoogleApiClient != null && mGoogleApiClient.isConnected(); 
    } 

    public void startFusedLocation() { 
     if (mGoogleApiClient == null) { 
      createLocationRequest(); 
      mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API) 
        .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() { 
         @Override 
         public void onConnectionSuspended(int cause) { 
         } 

         @Override 
         public void onConnected(Bundle connectionHint) { 

         } 
        }).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() { 

         @Override 
         public void onConnectionFailed(ConnectionResult result) { 

         } 
        }).build(); 
      mGoogleApiClient.connect(); 
     } else { 
      mGoogleApiClient.connect(); 
     } 
    } 

    public void stopLocationUpdates() { 
     LocationServices.FusedLocationApi.removeLocationUpdates(
       mGoogleApiClient, this); 
    } 

    public void stopFusedLocation() { 
     if (mGoogleApiClient != null) { 
      mGoogleApiClient.disconnect(); 
     } 
    } 

    public void setFusedLatitude(double lat) { 
     fusedLatitude = lat; 
    } 

    public void setFusedLongitude(double lon) { 
     fusedLongitude = lon; 
    } 

    public double getFusedLatitude() { 
     return fusedLatitude; 
    } 

    public double getFusedLongitude() { 
     return fusedLongitude; 
    } 

    public void createLocationRequest() { 
     mLocationRequest = LocationRequest.create(); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     mLocationRequest.setInterval(INTERVAL); 
     mLocationRequest.setFastestInterval(FASTEST_INTERVAL); 
    } 

    // check if google play services is installed on the device 
    private boolean checkPlayServices() { 
     int resultCode = GooglePlayServicesUtil 
       .isGooglePlayServicesAvailable(this); 
     if (resultCode != ConnectionResult.SUCCESS) { 
      if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { 
       Toast.makeText(getApplicationContext(), 
         "This device is supported. Please download google play services", Toast.LENGTH_LONG) 
         .show(); 
      } else { 
       Toast.makeText(getApplicationContext(), 
         "This device is not supported.", Toast.LENGTH_LONG) 
         .show(); 
      } 
      return false; 
     } 
     return true; 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     Toast.makeText(this, "!location.hasAccuracy(): " + (!location.hasAccuracy()) + ", location.getAccuracy(): " + (location.getAccuracy()), Toast.LENGTH_SHORT).show(); 

     /*if (!location.hasAccuracy()) { 
      return; 
     }*/ 
     if (location.getAccuracy() > 10) { 
      return; 
     } 
     setFusedLatitude(location.getLatitude()); 
     setFusedLongitude(location.getLongitude()); 
     Toast.makeText(this, "getFusedLatitude(): " + getFusedLatitude() + ", getFusedLongitude(): " + getFusedLongitude(), Toast.LENGTH_SHORT).show(); 
     Log.d("parkCar2", "Lat:" + getFusedLatitude() + ", lon: " + getFusedLongitude()); 
    } 

    @Override 
    public boolean onUnbind(Intent intent) { 
     stopLocationUpdates(); 
     return false; 
    } 

    @Override 
    public void onDestroy() { 
     stopFusedLocation(); 
     super.onDestroy(); 
    } 

    @Override 
    public IBinder onBind(Intent arg0) { 
     return myBinder; 
    } 

    public class GoogleMapServiceBinder extends Binder { 
     public GoogleMapService getServiceGoogle() { 
      return GoogleMapService.this; 
     } 
    } 
} 

Что я могу сделать для того, чтобы улучшить точ- местоположения службы в моем приложении? Заранее спасибо

ответ

1

Там пара вещей, которые вы можете сделать, чтобы улучшить точность определения местоположения:

  • обновление Запрос местоположение с LocationRequest.PRIORITY_HIGH_ACCURACY
  • Указать/разрешение запроса ACCESS_FINE_LOCATION, а не ACCESS_COARSE_LOCATION
  • В своем устройстве настройки местоположения, включите его и выберите с высокой точностью
  • Включить данные WiFi и сотовой связи
  • быть в месте с большим количеством WiFi мест общественного пользования рядом
  • Используйте приложение на открытом воздухе
  • Используйте последнюю библиотеку игры-сервисов местоположения
Смежные вопросы