【问题标题】:Android GPS tracks wrong locationAndroid GPS 跟踪错误的位置
【发布时间】:2016-07-01 20:48:21
【问题描述】:

在我的应用程序中,我想显示用户的当前位置,如果位置发生更改,它将显示更改位置的警报消息。问题是即使手机的 GPS 关闭,它也会显示位置更改消息。可能是什么原因?

这是我的代码:

 protected void onResume() {

    /**
     * get saved Location from shared preference
     * 
     */

    SharedPreferences sPrefs = PreferenceManager
            .getDefaultSharedPreferences(Activity_Home.this);
    String getL = sPrefs.getString(Utility.KEY_USER_LAT, "0.000000");
    String getLo = sPrefs.getString(Utility.KEY_USER_LONG, "0.000000");
    getLat = Double.parseDouble(getL);
    getLog = Double.parseDouble(getLo);
    gps = new GpsTracker(Activity_Home.this);

    /**
     * Get user current latitude and longitude and match them to stored
     * latitude and longitude if distance between these latitude then Pop up
     * will be show
     * 
     * @author Ankit
     */

    if (gps.canGetLocation()) {

        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();

        System.out.println("Latitude is " + getLat);

        if (getLat > 0.0) {
            Location locationA = new Location("point A");
            locationA.setLatitude(getLat);
            locationA.setLongitude(getLog);
            Location locationB = new Location("point B");
            locationB.setLatitude(latitude);
            locationB.setLongitude(longitude);
            distance = locationA.distanceTo(locationB);

            // Toast.makeText(Activity_Home.this,
            // "Distance is :"+Double.toString(distance),
            // Toast.LENGTH_LONG).show();
            distance = distance / 1000000;
            int getDistance = (int) (distance * 1000000);

            System.out.println("Distance is " + getDistance);
            if (getDistance > 100) {
                showWarningMessage();
            }
        }
        String lat = String.valueOf(latitude);
        String lon = String.valueOf(longitude);
        SharedPreferences sPref = PreferenceManager
                .getDefaultSharedPreferences(Activity_Home.this);
        SharedPreferences.Editor sEdit = sPref.edit();
        sEdit.putString(Utility.KEY_USER_LAT, lat);
        sEdit.putString(Utility.KEY_USER_LONG, lon);
        sEdit.commit();
    } else {
        gps.showSettingsAlert();
    }


    super.onResume();
}
// Method for show an Alert dialog for user if user's location changed''

public void showWarningMessage() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            Activity_Home.this);
    alertDialog.setCancelable(false);
    // Setting Dialog Title
    alertDialog.setTitle("Location Changed");

    // Setting Dialog Message
    alertDialog
            .setMessage("It seems your location has changed, would you like to change the Branch now?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Activity_Home.this,
                            Activity_Settings.class);
                    startActivity(intent);
                    dialog.cancel();
                }
            });

    // on pressing cancel button
    alertDialog.setNegativeButton("No",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    // Showing Alert Message
    alertDialog.show();
}




public class GpsTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 100; // 100 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

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

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

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        System.out.println("=====isGPSEnabled: 
 "+isGPSEnabled+"====isNetworkEnabled: "+isNetworkEnabled);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
            System.out.println("=====notgps");
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager

.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager

 .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GpsTracker.this);
    }      
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
  alertDialog.setCancelable(false);
    // Setting Dialog Title
    alertDialog.setTitle("Enable GPS");

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

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

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new   
 DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
   // alertDialog.;
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

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

}

【问题讨论】:

  • 呃,不是 GPSTracker.... 不要使用此代码.... 请参阅此处:gabesechansoftware.com/location-tracking
  • 如果您想在更改位置时使用onLocationChanged(Location location)
  • locationA.setLatitude(getLat);, locationA.setLongitude(getLog); GPS关闭时,这两条线会获取当前位置吗?或者它只会返回 0?
  • @HariKrishnan locationA.setLatitude(getLat);, locationA.setLongitude(getLog);将返回保存在共享首选项中的最后一个位置
  • 我有同样的问题。Gps 跟踪器显示我错了 lat long 。我也在尝试修复这个错误。

标签: android android-location android-gps


【解决方案1】:

这是一个查找位置的示例代码,检查它是否适合您

公共静态无效 LocationFind() {

    try {
        if (Skyhook) {
            _xps.getXPSLocation(null,
                    // note we convert _period to seconds
                    (int) (_period / 1000), _desiredXpsAccuracy, _callback);
            // _xps.getLocation(null, _streetAddressLookup, _callback);
        } else {
            Criteria criteria = new Criteria();
            criteria.setBearingRequired(false);
            criteria.setCostAllowed(true);
            criteria.setPowerRequirement(Criteria.POWER_LOW);
            criteria.setAltitudeRequired(false);
            criteria.setAccuracy(Criteria.ACCURACY_FINE);

            LocationManager locationManager = (LocationManager) mcontext.getSystemService(Context.LOCATION_SERVICE);

            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            // Getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
                // Log.d("Network", "Network");
                if (locationManager != null) {
                    lastknownlocations = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (lastknownlocations != null) {
                        lat = lastknownlocations.getLatitude();
                        lng = lastknownlocations.getLongitude();
                    }
                }
            }
            if (isGPSEnabled) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
                // Log.d("Network", "Network");
                if (locationManager != null) {
                    lastknownlocations = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (lastknownlocations != null) {
                        lat = lastknownlocations.getLatitude();
                        lng = lastknownlocations.getLongitude();
                    }
                }
            }
            if (lat == 0.0 && lng == 0.0) {
                lng = lastknownlocations.getLongitude();
                lat = lastknownlocations.getLatitude();
            }

            getAddressFromLatLong(lat, lng);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

【讨论】:

    【解决方案2】:

    试试这个服务类。每当10 meters 与最后一个位置不同时,这就会向方法sendLocationDataToProcess(Location location) 发送更新

    public class AppLocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener,
            LocationListener{
    
        private LocationRequest locationRequest;
        private GoogleApiClient googleApiClient;
        private Context appContext;
        private boolean currentlyProcessingLocation = false;
        private int mInterval=0;
        private final int CONNTIMEOUT=50000;
        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            appContext=getApplicationContext();
            Toast.makeText(getBaseContext(), "Location Service Started", Toast.LENGTH_SHORT)
                    .show();
            if (!currentlyProcessingLocation) {
                currentlyProcessingLocation = true;
                startTracking();
            }
    
            return START_STICKY;
        }   
        private void startTracking() {
    
            if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
                Log.v(Constants.BLL_LOG, "ConnectionResult SUCCESS");
                googleApiClient = new GoogleApiClient.Builder(this)
                        .addApi(LocationServices.API)
                        .addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this)
                        .build();
    
                if (!googleApiClient.isConnected() || !googleApiClient.isConnecting()) {
                    googleApiClient.connect();
                }else{
                    Log.v(Constants.BLL_LOG, "NOT connected googleApiClient.connect()");
                }
            } else {
                Log.v(Constants.BLL_LOG, "unable to connect to google play services.");
            }
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
        public AppLocationService() {
        }
        @Override
        public void onConnected(Bundle bundle) {
            Log.v(Constants.BLL_LOG,"onConnected");
            locationRequest = LocationRequest.create();
            locationRequest.setInterval(mInterval * 1000); // milliseconds
            locationRequest.setFastestInterval(mInterval * 1000);
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setSmallestDisplacement(MIN_DISTANCE_CHANGE_FOR_UPDATES);//dostance change
            int permissionCheck = ContextCompat.checkSelfPermission(appContext, Manifest.permission.ACCESS_COARSE_LOCATION);
            if (permissionCheck!= PackageManager.PERMISSION_DENIED)
                LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
        }   
    
        @Override
        public void onConnectionSuspended(int i) {
            Log.v(Constants.BLL_LOG,"onConnectionSuspended");
        }
    
        @Override
        public void onLocationChanged(Location location) {
            Log.v(Constants.BLL_LOG, "onLocationChanged position: " + location.getLatitude() + ", " + location.getLongitude() + " accuracy: " + location.getAccuracy());
            Log.v(Constants.BLL_LOG, "onLocationChanged position: location.getAccuracy()= "+location.getAccuracy());
            sendLocationDataToProcess(location);
        }
    
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            Log.v(Constants.BLL_LOG,"onConnectionFailed");
        }
    
        void sendLocationDataToProcess(Location location){
            //Do your logic with Location data
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            if (googleApiClient != null && googleApiClient.isConnected()) {
                googleApiClient.disconnect();
            }
        }       
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 2017-03-03
      • 2013-01-02
      • 2023-03-26
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多