我需要你的幫助,關於android中的位置更新。以下是我的代碼獲取位置更新,它工作正常。但是當我在主類的oncreate方法中獲取存儲的變量時,它返回無效的消息體。經過深入研究,似乎我在oncreate方法中調用的變量是空的。你能告訴我如何獲取地址,因爲它出現在onlocationChanged方法中。謝謝!從位置監聽器調用和獲取oncreate方法的位置android
調用類onCreate方法:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new Mylocation();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
String address1= listener.getAddress();
{
sendSms(phone, message, false);
} catch (Exception e) {
Log.i("Error Is ", e.toString());
}
}
位置類:
class Mylocation implements LocationListener{
double lat, lon;
static final String address="";
public void onLocationChanged(Location location)
{
//...
lat = location.getLatitude();
lon = location.getLongitude();
address = GetAddressDetail(lat, lon);
Log.i("Messge is", address); //working here
}
public String getAddress(){ //not returning the address
return address;
}
public String GetAddressDetail(Double lat2, Double lon2)
{
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}
}
您的地址變量是最終的,這意味着它只能分配一次。因此,將其重新分配給GetAdressDetail結果將不起作用。 – 2013-04-23 12:03:49
它沒有出現,你已經爲'message'聲明瞭一個值,並且你沒有顯示它的實例化。 – jnthnjns 2013-04-23 12:07:19
@LeonLucardie,雖然地址被宣佈爲最終它仍然在那部分工作。唯一的是我不能通過getAddress在Android的 – 2013-04-23 12:10:31