LocationManager mLocationManager;
Location mLocation;
mLocationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
tv = (TextView)findViewById(R.id.text);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String locationprovider = mLocationManager.getBestProvider(criteria, true);
mLocationManager.requestLocationUpdates(locationprovider, 5000, (float) 1.0, this);
// mLocation = mLocationManager.getLastKnownLocation(locationprovider); //一开始不要使用,容易返回null
tv.setText("Last location lat :" + mLocation.getLatitude());
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), "location", Toast.LENGTH_LONG).show();
mLocation = location;
showupdate();
List<Address> addresses;
try {
Geocoder mGC = new Geocoder(this, Locale.ENGLISH);
addresses = mGC.getFromLocation(mLocation.getLatitude(), mLocation.getLongitude(),1);
if(addresses != null){
Address currentAddress = addresses.get(0);
StringBuilder sb = new StringBuilder("Address:\n");
for(int i=0;i<currentAddress.getMaxAddressLineIndex();i++){
sb.append(currentAddress.getAddressLine(i)).append("\n");
}
tv.setText(sb.toString());
}
} catch (Exception e) {
// TODO: handle exception
//Toast.makeText(getApplicationContext(), "error."+e.getMessage(), Toast.LENGTH_LONG).show();
if(location != null)
{
double x = location.getLatitude();
double y = location.getLongitude();
String address = "http://maps.google.cn/maps/api/geocode/xml?latlng="+x+","+y+"&sensor=true&language=zh-CN";
//http://maps.google.cn/maps/api/geocode/xml?latlng=31.2398790,121.4996740&sensor=true&language=zh-CN
try {
URL url = new URL(address);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
InputStream input = http.getInputStream();
byte[] bt = new byte[1024];
int n;
StringBuilder sb =new StringBuilder();
while((n=input.read(bt, 0, bt.length))!= -1){
sb.append(new String(bt,0,n));
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "url error", Toast.LENGTH_LONG).show();
e1.printStackTrace();
} catch (IOException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
}
}
//showupdate();
}
private void showupdate() {
// TODO Auto-generated method stub
tv.setText("Last location lat :" + mLocation.getLatitude()+" long:"+mLocation.getLongitude());
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}