当用户在应用程序打开时打开位置时,我获取位置的时间太晚了。这是我的 GPSTracking 代码

I am getting location too late when the user turns on the location when the app is open. here's my GPSTracking code

我是 Android 的新手,创建一个基于位置的简单应用程序。 当用户在没有打开位置的情况下打开应用程序时,它将直接进入设置,如果他们打开,那么我就是 获取经纬度值太晚了。

    import android.Manifest;
    import android.app.AlertDialog;
    import android.app.Service;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.provider.Settings;
    import android.support.v4.app.ActivityCompat;

    public class GPSTracking extends Service implements LocationListener
    {

        private final Context mContext;

        boolean isGPSEnabled = false;
        boolean isNetworkEnabled = false;
        private boolean canGetLocation = false;

        Location mLocation;
        private double lat;
        private double lng;

        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE = 10;

        private static final long MIN_TIME_BW_UPDATE = 1000 * 60 * 1;

        protected LocationManager locationManager;

        public GPSTracking(Context context) 
        {
            this.mContext = context;
            getLocation();
        }


        public Location getLocation() 
        {
            try 
            {
                locationManager = (LocationManager) 
                mContext.getSystemService(LOCATION_SERVICE);
                isGPSEnabled = 

             locationManager.isProviderEnabled(lo
             cationManager.GPS_PROVIDER);
                isNetworkEnabled = 


                locationManager.isProviderEnabled(locat
                ionManager.NETWORK_PROVIDER);

                if (!isGPSEnabled && !isNetworkEnabled)
                {
                    //no network or gps
                }
                else
                {
                    setCanGetLocation(true);

                    if (isNetworkEnabled) 
                    {
                        if(locationManager!=null)
                        {
                            mLocation = 
                            locationManager.getLastKnownLocation
                            (LocationManager.NETWORK_PROVIDER);
                            if(mLocation!=null)
                            {
                                setLat(mLocation.getLatitude());
                                setLng(mLocation.getLongitude());
                            }
                        }
                    }
                    if (isGPSEnabled)
                    {
                        if (mLocation == null) 
                        {
                            locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATE,
                            MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
                            if (locationManager != null) 
                            {
                                        mLocation = locationManager

                                       .getLastKnownLocation(LocationManager
                                       .GPS_PROVIDER);
                                        if (mLocation != null) 
                                        {
                                            setLat(mLocation.getLatitude());
                                            setLng(mLocation.getLongitude());
                                        }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                    //Exception 

            }

            return mLocation;
        }

        public void showAlertDialog()
        {
                AlertDialog.Builder alertDialog = new 
                AlertDialog.Builder(mContext);

                alertDialog.setTitle("GPS is settings");

                alertDialog.setMessage("GPS is not enabled. Do you want go to 
                settings menu?");

                alertDialog.setPositiveButton("Settings", new 
                DialogInterface.OnClickListener() 
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which) 
                    {
                        Intent intent = new 
                        Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mContext.startActivity(intent);
                    }
                });

                alertDialog.setNegativeButton("Cancel", new 
                DialogInterface.OnClickListener() 
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which) 
                    {
                        dialog.cancel();
                    }
                });

                alertDialog.show();
        }

        @Override
        public IBinder onBind(Intent intent) {
            // TODO: Return the communication channel to the service.
            throw new UnsupportedOperationException("Not yet implemented");
        }

        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle 
      extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider)
        {
            //Toast.makeText(mContext, "Please turn on the location", 
             // Toast.LENGTH_SHORT).show();
        }

        public double getLat() {
            return lat;
        }

        public void setLat(double lat) {
            this.lat = lat;
        }

        public double getLng() {
            return lng;
        }

        public void setLng(double lng) {
            this.lng = lng; //this is the lat
        }

        public boolean isCanGetLocation() {
            return canGetLocation;
        }

        public void setCanGetLocation(boolean canGetLocation)
        {
            this.canGetLocation = canGetLocation; //this is canGetLocation which will do the following thing.
        }



    }`*

据我所知,这取决于 phone、wifi 打开或关闭、准确性

还有三种类型的位置:

GPS_PROVIDER
NETWORK_PROVIDER
PASSIVE_PROVIDER

所以,根据我的经验,我知道如果你使用:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, new     MyLocationListener());

您将获得高达 14 位以上小数位的精度。

但是如果你像这样使用它们的融合:

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, my_google_listener);

您将获得高达 6 到 7 位小数的精度。尝试一下 !!!参考

但请注意这里的一些事情,GPS 提供程序需要时间来获取位置,而 Google 定位要快得多,因为它从 API 调用其 google 服务器数据库获取数据。

GPS 离线工作,而 google 提供商通过移动或 wifi 数据获取位置。

您可以尝试 google api 获取用户位置的客户端试试这个

它会像其他 google 应用程序一样在设置中打开位置而不导航

public class ActivitySignUp extends BaseActivity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

private Location mylocation;
    private GoogleApiClient googleApiClient;
    private final static int REQUEST_CHECK_SETTINGS_GPS = 0x1;
    private final static int REQUEST_ID_MULTIPLE_PERMISSIONS = 0x2;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signup_activity);

        setUpGClient();
    }

 //set user api client for access location
    private synchronized void setUpGClient() {
        googleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, 0, this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        googleApiClient.connect();

    }

    @Override
    public void onLocationChanged(Location location) {
        mylocation = location;
        if (mylocation != null) {
            Double latitude = mylocation.getLatitude();
            Double longitude = mylocation.getLongitude();

            if (latitude != 0 && longitude != 0) {
                Log.e("Lat Long", "Lat " + latitude + " && Long " + longitude);
               //here is your lat long
                if (googleApiClient.isConnected()) {
                    googleApiClient.disconnect();
                }
            }
            //Or Do whatever you want with your location
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        checkPermissions();
    }

    @Override
    public void onConnectionSuspended(int i) {
        //Do whatever you need
        //You can display a message here
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        //You can display a message here
    }

    private void getMyLocation() {
        if (googleApiClient != null) {
            if (googleApiClient.isConnected()) {
                int permissionLocation = ContextCompat.checkSelfPermission(ActivitySignUp.this,
                        Manifest.permission.ACCESS_FINE_LOCATION);
                if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
                    mylocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
                    LocationRequest locationRequest = new LocationRequest();
                    locationRequest.setInterval(3000);
                    locationRequest.setFastestInterval(3000);
                    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                            .addLocationRequest(locationRequest);
                    builder.setAlwaysShow(true);
                    LocationServices.FusedLocationApi
                            .requestLocationUpdates(googleApiClient, locationRequest, ActivitySignUp.this);
                    PendingResult<LocationSettingsResult> result =
                            LocationServices.SettingsApi
                                    .checkLocationSettings(googleApiClient, builder.build());
                    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {

                        @Override
                        public void onResult(LocationSettingsResult result) {
                            final Status status = result.getStatus();
                            switch (status.getStatusCode()) {
                                case LocationSettingsStatusCodes.SUCCESS:
                                    // All location settings are satisfied.
                                    // You can initialize location requests here.
                                    int permissionLocation = ContextCompat
                                            .checkSelfPermission(ActivitySignUp.this,
                                                    Manifest.permission.ACCESS_FINE_LOCATION);
                                    if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
                                        mylocation = LocationServices.FusedLocationApi
                                                .getLastLocation(googleApiClient);
                                    }
                                    break;
                                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                    // Location settings are not satisfied.
                                    // But could be fixed by showing the user a dialog.
                                    try {
                                        // Show the dialog by calling startResolutionForResult(),
                                        // and check the result in onActivityResult().
                                        // Ask to turn on GPS automatically
                                        status.startResolutionForResult(ActivitySignUp.this,
                                                REQUEST_CHECK_SETTINGS_GPS);
                                    } catch (IntentSender.SendIntentException e) {
                                        // Ignore the error.
                                    }
                                    break;
                                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:

                                    break;
                            }
                        }
                    });
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CHECK_SETTINGS_GPS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        getMyLocation();
                        break;
                    case Activity.RESULT_CANCELED:
                        finish();
                        break;
                }
                break;
        }
    }

    private void checkPermissions() {
        int permissionLocation = ContextCompat.checkSelfPermission(ActivitySignUp.this,
                android.Manifest.permission.ACCESS_FINE_LOCATION);
        List<String> listPermissionsNeeded = new ArrayList<>();
        if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(this,
                        listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
            }
        } else {
            getMyLocation();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        int permissionLocation = ContextCompat.checkSelfPermission(ActivitySignUp.this,
                Manifest.permission.ACCESS_FINE_LOCATION);
        if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
            getMyLocation();
        }
    }

如果有帮助请告诉我