【问题标题】:I am getting location too late when the user turns on the location when the app is open. here's my GPSTracking code当用户在应用程序打开时打开位置时,我获取位置太晚了。这是我的 GPSTracking 代码
【发布时间】:2018-07-02 10:48:45
【问题描述】:

我是 Android 新手,根据位置创建一个简单的应用程序。 当用户在不打开位置的情况下打开应用程序时,它将直接进入设置,如果他们打开则从那里进入 获取 lat 和 lang 值为时已晚。

    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.
        }



    }`*

【问题讨论】:

  • 很遗憾,您选择了错误的示例代码。这种方法通常被称为“GPSTracker”,它有一些问题,例如它extends Service,但实际上并没有真正用作服务,它请求位置更新,但不在onLocationChanged() 中处理它们.不过它可能工作得很好。居然有人写了a detailed blog post about the problems in that code
  • 哦,知道了。非常感谢。

标签: android android-gps


【解决方案1】:

你可以试试 google api 客户端来获取用户位置试试这个

它将打开位置信息,而无需像其他谷歌应用程序那样在设置中导航

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();
        }
    }

如果有帮助请告诉我

【讨论】:

  • 正是我需要的。非常感谢!
  • 快乐编码 :-)
【解决方案2】:

据我所知,这取决于手机、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 Provider 需要时间来获取位置,而 Google Location 则要快得多,因为它从 API 调用获取数据到其 google 服务器数据库。

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

【讨论】:

  • 谢谢。现在,当我开始使用 mGoogleApiClient 时,该应用程序运行良好
猜你喜欢
  • 2014-08-07
  • 1970-01-01
  • 2015-11-18
  • 2017-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多