0
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); 

我发现使用上述代码更改位置时,onLocationChanged 函数可以正常工作。

///////CLASS  mylocationlistener
private class mylocationlistener implements LocationListener {
    //@Override
    public void onLocationChanged(Location location) {
        if (location != null) {
        Log.d("LOCATION CHANGED", location.getLatitude() + "");
        Log.d("LOCATION CHANGED", location.getLongitude() + "");
        Toast.makeText(MainActivity.this,
            location.getLatitude() + "" + location.getLongitude(),
            Toast.LENGTH_LONG).show();
        p = new GeoPoint((int)location.getLatitude(),(int)location.getLongitude());

       // p = new GeoPoint((int)8.538754,(int)76.950620);
        }
    }
    //@Override
    public void onProviderDisabled(String provider) {
    }
   // @Override
    public void onProviderEnabled(String provider) {
    }
   // @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    }

但问题是我希望变量“p”填充当前位置,当程序启动时,即在第一次更改帮助之前!

4

2 回答 2

0

试试这个代码:

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);

// Initialize the location fields
if (location != null) {
  System.out.println("Provider " + provider + " has been selected.");
  onLocationChanged(location);
} else {
  latituteField.setText("Location not available");
  longitudeField.setText("Location not available");
  System.out.println("Location not avilable");
}
}

/* Request updates at startup */
@Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}

/* Remove the locationlistener updates when Activity is paused */
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}

@Override
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
Log.i(TAG, "Lattitude:" +lat);
Log.i(TAG, "Longitude:" +lng);
}
于 2012-09-28T05:28:26.730 回答
0

在你得到修复之前,你可以使用粗略的位置。检查此链接: http ://devdiscoveries.wordpress.com/2010/02/04/android-use-location-services/

于 2012-09-28T06:50:27.923 回答