onLocationChanged()开始得太晚了,我无法按时获得经纬度

时间:2016-02-17 07:11:45

标签: android geolocation

我试图使用onLocationChanged()方法获取手机的纬度和经度但该方法执行得太晚且vars在JsonRequest中包含0.0,任何想法我怎么做才能启动onLocationChangedMethod onCreate()?

有我的代码:

  package weatheralarm.valbol.oshrim.final_alarmproject;

import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

public class PresentWeatherAdvice extends AppCompatActivity implements LocationListener {
    final String PATH = "http://api.openweathermap.org/data/2.5/forecast?q=";
    final String GPSPATH = "http://api.openweathermap.org/data/2.5/forecast?lat=";
    final String GPSPATH1 = "&lon=";
    final String SUFFIX = "&units=metric&mode=json&appid=f69e8280457b8e7fe2e954aae1444";
    private final int DISTANCE = 5, AFTERMILLISECS = 100;
    private LocationManager locationManager;
    private ArrayList<Weather> listArr;
    String url;
    private double latitude, longitude;
    SharedPreferences prefs;
    private final String PREFSNAME = "alarmClockSet";
    private final String LONKEY = "lonKey";
    private final String LATKEY = "latKey";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_present_weather_advice);
        prefs = this.getSharedPreferences(PREFSNAME, MODE_PRIVATE);
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        //request udpate if user changed location or after time
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, AFTERMILLISECS, DISTANCE, (LocationListener) this);
     //   latitude = Double.parseDouble(prefs.getString(LATKEY,"0.0"));
      //  longitude = Double.parseDouble(prefs.getString(LONKEY,"1.1"));
        url = GPSPATH + latitude + GPSPATH1 + longitude + SUFFIX;
        Log.i("url","url: " + url + " lat " + latitude);
        //getWeather(url, this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        getWeather(url,this);
    }

    private void getWeather(String url,Context context){

        final RequestQueue queue = Volley.newRequestQueue(context);
        Log.i("url", url);
        Log.i("TAG", "lati-getW" + latitude);

        final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            String icon, date, temp, desc, iconPath;
                            JSONArray jsonArray = response.getJSONArray("list");


                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject dt = jsonArray.getJSONObject(i);
                                Log.i("dt " + i + " ", dt.toString());
                                date = dt.getString("dt_txt");
                                Log.i("date", date);
                                icon = dt.getJSONArray("weather").getJSONObject(0).getString("icon");
                                iconPath = " http://openweathermap.org/img/w/" + icon + ".png";
                                Log.i("icon", icon);
                                desc = dt.getJSONArray("weather").getJSONObject(0).getString("description");
                                Log.i("desc", desc);
                                temp = dt.getJSONObject("main").getString("temp");
                                Log.i("temp", temp);
                                Weather weather = new Weather(iconPath, date, temp, desc);
                                listArr.add(weather);
                            }

                            for (int i = 0; i < listArr.size(); i++) {
                                Log.i("TAG", "ListArr: " + listArr.get(i).getDate());

                            }
                        }catch (Exception e){

                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }


    @Override
    public void onLocationChanged(Location location) {
        Log.i("in location", " lat " + latitude +" lon "+ longitude);
        this.longitude = location.getLongitude();
        this.latitude = location.getLatitude();
        Log.i("in location", " lat " + latitude +" lon "+ longitude);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用getLastLocation而不是等待变量latitudelongitude更新,而archive.org from March 18, 2015将返回最新的最新位置。您不能依赖onLocationChanged进行更新(或者您可以选择在其中激活JsonObjectRequest),因为只有在新位置可用时才会调用它,并且取决于设备及其传感器可随时调用。