在oncreate方法中从location listener调用和获取location出现问题



我需要你的帮助关于android的位置更新。以下是我的代码获取位置更新,它工作得很好。但是当我在主类的oncreate方法中获得存储变量的位置时,它返回无效的消息体。经过深入研究,我在oncreate方法中调用的变量似乎是空的。你能告诉我如何获取onlocationChanged Method中显示的地址吗?谢谢你!

用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;
}
}

确保变量被正确初始化。我在问题中没有看到这方面的证据,所以我只是检查一下。

// Instantiation
Mylocation listener;
String phone;
String message;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Initialization
    listener = new Mylocation(this);
    phone = "";
    message = "";
    // These two lines aren't really necessary,
    // this should be in your MyLocation class      
    //locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
    // Add this line, we are going to initialize this class 
    // and make sure that address gets set
    listener = new Mylocation();
    String address1 = listener.getAddress();
    try {
        // If neither phone nor message is empty lets sendSms()
        if (!phone.isEmpty() || !message.isEmpty()) {
            sendSms(phone, message, false);
        }
    } catch (Exception e) {
        Log.i("Error Is ", e.toString());
    }
}

String address更改为private,并在getter中尝试return this.address;

class Mylocation implements LocationListener {
    double lat, lon;
    // Let's make this private so it can't be accessed directly, 
    // since you have the setter and getter.
    private String address = "";
    // Make sure you are overriding this method
    @Override    
    public void onLocationChanged(Location location) {
        /** ... */
        lat = location.getLatitude();
        lon = location.getLongitude();
        address = GetAddressDetail(lat, lon);
        Log.i("Messge is", address);
    }
    public String getAddress(){
        return (address.isEmpty()) ? "Address not set" : this.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;
    }
}

编辑

我在上面的回答中修改了你的代码,检查注释。我还将为您的MyLocation类建议其他方法:

class Mylocation implements LocationListener {
    protected LocationManager locationManager;
    private Context activityContext;
    // The initializing method, this fires off first 
    // when a new instance of the class is created
    public MyLocation(Context context) {
        this.activityContext = context;
        locationManager = (LocationManager) activityContext.getSystemService(LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);) {
            locationManager.requestLocationUpdates(
                NETWORK_PROVIDER, 
                MIN_TIME, 
                MIN_DISTANCE, 
                this
            );
        }
        getLocation();
    }
    private double lat;
    private double lon;
    public double getLat() {
        return this.lat;
    }
    public double getLng() {
        return this.lng;
    }
    public void getLocation() {
        if (location == null) {
            locationManager.requestLocationUpdates(NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
            if (locationManager != null) {
                location = locationManager.getLastKnownLocation(NETWORK_PROVIDER);
                if (location != null) {
                    // Set the coordinate variables
                    lat = location.getLatitude();
                    lon = location.getLongitude();
                    Log.i("Network", "Lat: " + latitude + " / Lng: " + longitude);
                }
            }
        }
    }
}

在设置locationmanager以探测位置之后直接调用getaddress。当你以这种方式调用getAddress时,onLocationChanged方法可能还没有被调用。我建议将其更改为如下所示,以确保它已被称为:

 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,new LocationListener(){
           @Override    
           public void onLocationChanged(Location location) {
           //...
              long lat = location.getLatitude();
              long lon = location.getLongitude();
              String address = GetAddressDetail(lat, lon);
              //Do whatever you want to do with the address here, maybe add them to the message or something like that.
              sendSms(phone, message, false);
           }
      });
}
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;
}

最新更新