具体方法如下:
public void getLocation() throws IOException {
TextView tv = (TextView)this.findViewById(R.id.mytextView);
StringBuffer sb = new StringBuffer();
Location loc;
LocationManager locMan;
LocationProvider locPro;
List<LocationProvider> proList;
locMan = (LocationManager)this.getSystemService(LOCATION_SERVICE);
List<String> providers = locMan.getProviders(true);
for(String provider : providers) {
Log.i(TAG, provider);
System.out.println("--------------------------------"+provider);
locMan.requestLocationUpdates(provider,
1000, 0,
new LocationListener(){
public void onLocationChanged(
Location location) {
// TODO Auto-generated method stub
}
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
}});
Location location = locMan.getLastKnownLocation(provider);
//Location location = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//Location location = locMan.getProvider(LocationManager.GPS_PROVIDER);
if(location!=null) {
sb.append("lat:").append(location.getLatitude()).append(",").append(location.getLongitude());
Geocoder gc = new Geocoder(this, Locale.getDefault());
List<Address> addresses = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 10);
if(addresses.size() > 0) {
Address address = addresses.get(0);
for(int i = 0; i < address.getMaxAddressLineIndex(); i ++) {
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName()).append("\n");
}
}
} else {
sb.append("No Location");
}
tv.setText(sb);
}
}
权限为<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>