1

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

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

2 回答 2

2

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

// 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为私有并在 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);
                }
            }
        }
    }
}
于 2013-04-23T12:17:35.227 回答
1

在将 locationmanager 设置为探测位置后,您将直接调用 getAdress。当您以这种方式调用 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;
}
于 2013-04-23T13:53:38.320 回答