简体   繁体   English

麻烦调用并从位置监听器android获取oncreate方法中的位置

[英]Trouble calling and getting location in oncreate method from location listener android

i need your help regarding the location update in android. 我需要你关于android中位置更新的帮助。 Following is my code for getting location update and it is working fine. 以下是我获取位置更新的代码,它运行正常。 But it returns invalid message body when i get the stored variable with location in oncreate method of main class. 但是当我在主类的oncreate方法中获取带位置的存储变量时,它返回无效的消息体。 After thorough research it seems that the variable i called in oncreate method is empty. 经过深入研究后,似乎我在oncreate方法中调用的变量是空的。 Can you please tell me how to get the address as it appears in onlocationChanged Method. 您能告诉我如何获取onlocationChanged方法中显示的地址。 Thank you! 谢谢!

Calling class with oncreate 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());
            }

        }

location class: 位置等级:

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

Make sure your variables are initialized properly. 确保您的变量已正确初始化。 I don't see evidence of this in the question so I am just checking. 我在问题中没有看到这方面的证据所以我只是在检查。

// 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());
    }

}

Change the String address to private and in the getter try return this.address; 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;
    }
}

Edit 编辑

I made changes to your code in my answer above, check the comments. 我在上面的答案中对您的代码进行了更改,请查看注释。 I am also going to suggest additional methods for your MyLocation class: 我还将为您的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);
                }
            }
        }
    }
}

You are calling getAdress directly after you set the locationmanager to probe for a location. 在将locationmanager设置为探测位置后,您将直接调用getAdress。 The onLocationChanged method probably hasn't been called yet when you call getAddress this way. 当您以这种方式调用getAddress时,可能还没有调用onLocationChanged方法。 I would recommend changing it to something like below to make sure it has been called: 我建议将其更改为类似下面的内容,以确保它已被调用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM