Android GPS位置未被更改

Android GPS位置未被更改,android,gps,location,Android,Gps,Location,我正在编写一个简单的应用程序,需要从a点设置当前的GPS坐标,然后移动到另一个B点,让它检测B点的坐标。我可以毫无问题地获得a点坐标。我只是没有让它检测B点的坐标,它读取的坐标与A点的坐标相同。我已经在手机上安装了应用程序,我正在两个点之间行驶一英里。我的清单文件包含所有可能的位置权限 这是活动代码 public class GPSTrackingActivity extends Activity { Button btnShowLocation; Button btnShowEndLocat

我正在编写一个简单的应用程序,需要从a点设置当前的GPS坐标,然后移动到另一个B点,让它检测B点的坐标。我可以毫无问题地获得a点坐标。我只是没有让它检测B点的坐标,它读取的坐标与A点的坐标相同。我已经在手机上安装了应用程序,我正在两个点之间行驶一英里。我的清单文件包含所有可能的位置权限

这是活动代码

public class GPSTrackingActivity extends Activity {

Button btnShowLocation;
Button btnShowEndLocation;

// GPSTracker class
GPSTracker gps;

TextView tvIntialLocation;
TextView tvEndLocation;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    myDBHelper = new DataBaseHelper(GPSTrackingActivity.this);
    tvIntialLocation = (TextView)findViewById(R.id.tvIntialLocation);
    tvEndLocation = (TextView)findViewById(R.id.tvEndLocation);

    // create class object
    gps = new GPSTracker(GPSTrackingActivity.this);     


    btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
    btnShowEndLocation = (Button)findViewById(R.id.btnEndLocation);

    // show location button click event
    btnShowLocation.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            // check if GPS enabled
            if(gps.canGetLocation()){

                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();
                tvIntialLocation.setText("Start Location is - \nLat: " + latitude + "\nLong: " + longitude);

               }else{
                // can't get location
                // GPS or Network is not enabled
                // Ask user to enable GPS/network in settings
                gps.showSettingsAlert();
            }

        }
    });

 // show location button click event
    btnShowEndLocation.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            // check if GPS enabled
            if(gps.canGetLocation()){

                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();
                tvEndLocation.setText("End Location is - \nLat: " + latitude + "\nLong: " + longitude);

            }else{
                // can't get location
                // GPS or Network is not enabled
                // Ask user to enable GPS/network in settings
                gps.showSettingsAlert();
            }

        }
    });

}
}

下面是设置GPS跟踪器类的课程。我不确定是否有人呼叫onLocationChanged,在我开车时,当位置改变时,我没有看到任何Toast消息

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 = 10; // 10 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);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } 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;
}


/**
 * 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;
}


@Override
public void onLocationChanged(Location location) {
    location = getLocation();
    // Testing onLocationChanged:
    String hej1 = Double.toString(location.getLatitude());
    String hej2 = Double.toString(location.getLongitude());
    Toast.makeText(this, "Location: "+"Lat: " + hej1 + "Long: " + hej2,
            Toast.LENGTH_LONG).show();
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

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


为什么第二个点没有更新到当前位置?起点和终点显示为相同的GPS坐标

onLocationChanged更改为以下代码

    @Override
    public void onLocationChanged(Location location) {
        this.location = location;
        // Testing onLocationChanged:
        String hej1 = Double.toString(location.getLatitude());
        String hej2 = Double.toString(location.getLongitude());
        Toast.makeText(this, "Location: "+"Lat: " + hej1 + "Long: " + hej2,
            Toast.LENGTH_LONG).show();
    }

您应该在类成员前面加上m,例如Location mLocation

您正在使用的
getLastKnownLocation
对于获取更新位置总是不起作用

我也有同样的问题。我终于解决了。您可以使用google
FusedLocationApi
获取位置更新,就像google地图应用程序一样

服务中的代码示例:

 @Override
    public void onCreate() {
if (checkPlayServices()) {

            startFusedLocation();

            registerRequestUpdate(this);
        }
}

 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;
    }
 public void startFusedLocation() {
        if (mGoogleApiClient == null) {
            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 stopFusedLocation() {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.disconnect();
        }
    }

    public void registerRequestUpdate(final LocationListener listener) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        mLocationRequest.setInterval(1000); // every second
        //mLocationRequest.setFastestInterval(NOTIFY_INTERVAL/2);


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, listener);
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                    if (!isGoogleApiClientConnected()) {
                        mGoogleApiClient.connect();
                    }

                    registerRequestUpdate(listener);


                }
            }
        }, 1000);
    }

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

    @Override
    public void onLocationChanged(Location location) {      
        double lat = location.getLatitude();
        double lon = location.getLongitude();
        Toast.makeText(getApplicationContext(), "NEW LOCATION RECEIVED", Toast.LENGTH_LONG).show();


        String Provider=location.getProvider();

        Log.d("location", "IN ON LOCATION CHANGE, lat=" + lat + ", lon=" + lon);

        //locationManager.removeUpdates(this);

    }

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

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

    public double getFusedLatitude() {
        return fusedLatitude;
    }

    public double getFusedLongitude() {
        return fusedLongitude;
    }

谢谢,但那不行。点B的坐标仍然不变。是否显示onLocationChanged的toast。如果没有toast,则永远不会调用它。不,toast从不显示,因此永远不会调用onLocationChanged。这意味着永远不会调用onLocationChanged,这就是位置没有变化的原因。尝试locationManager.RequestLocationUpdate(locationManager.GPS\u提供程序,0,0,此);查看您是否有土司。您的代码仅在未启用网络位置更新时请求GPS位置更新。因此,如果你不移动到很远的地方,你将不会得到任何更新。我建议您删除getLocation方法中if(isGPSEnabled)之后的if(location==null)行。