我正在尝试显示当前位置和经度、纬度。我可以轻松获取经度和纬度,但无法显示当前位置。我在下面显示我的代码。
public class MainActivity extends Activity implements LocationListener{
LocationManager locationManager ;
String provider;
Context context;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
{
onLocationChanged(location);
//Toast.makeText(getApplicationContext(),"Hello1",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onLocationChanged(final Location location) {
// Getting reference to TextView tv_longitude
TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);
// Getting reference to TextView tv_latitude
TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);
// Setting Current Longitude
tvLongitude.setText("Longitude:" + location.getLongitude());
// Setting Current Latitude
tvLatitude.setText("Latitude:" + location.getLatitude() );
// From here i want to get the location, as i pass current longitude &
这里的纬度。它在地址中传递 null 意味着它在这里执行 else 而不是 if。
try {
Toast.makeText(getApplicationContext(),"Hello1",Toast.LENGTH_SHORT).show();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses != null ) {
Address address = addresses.get(0);
// sending back first address line and locality
String result = address.getAddressLine(0) + ", " + address.getLocality();
Toast.makeText(getApplicationContext(),"result",Toast.LENGTH_SHORT).show();
}
if (addresses.size() > 0) {
String address = "";
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
Log.v("AddressTag", address);
}
else
{
Toast.makeText(getApplicationContext(),"Hello2",Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}