簡體   English   中英

麻煩調用並從位置監聽器android獲取oncreate方法中的位置

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

我需要你關於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;
}
}

確保您的變量已正確初始化。 我在問題中沒有看到這方面的證據所以我只是在檢查。

// 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設置為探測位置后,您將直接調用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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM