public class Locationfinder extends Activity implements LocationListener{
private TextView latituteField,longitudeField, Address;
private LocationManager locationManager;
private String provider;
List<Address> mAddresses;
double lat,lng;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
Address=(TextView)findViewById(R.id.TextView03);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
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) {
// TODO Auto-generated method stub
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
System.out.println("lat1: " + lat +" " +"lng1" +lng);
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
Geocoder gcd = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {
mAddresses = gcd.getFromLocation(lat,lng, 1);
String address = mAddresses.get(0).getAddressLine(0);
String city = mAddresses.get(0).getAddressLine(1);
String country = mAddresses.get(0).getAddressLine(2);
Address.setText("Address:- " + address + "city :" +city + "country : "+ country);
} catch (IOException e) {
e.printStackTrace();
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Disable GPS " + provider,
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Enable GPS " + provider,
Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
謝謝。甚至在我找到解決方案後回答道具。 –
不用擔心男人,認爲它會幫助你出於簡單起見 – Demitrian