Android位置:使用AsyncTask进行简单的一次性GPS提取

时间:2015-06-23 00:58:07

标签: android asynchronous gps location

我尝试使用上一个已知位置更新静态变量纬度和经度。

类别:

    class FetchGPS extends AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {
        new_latitude = 0.0;
        new_longitude = 0.0;
    }

    @Override
    protected String doInBackground(String... params) {
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        while (new_latitude == 0.0) {
            try {
                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                new_latitude = location.getLatitude();
                new_longitude = location.getLongitude();
            } catch (Exception e1) {
                try {
                    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    new_latitude = location.getLatitude();
                    new_longitude = location.getLongitude();
                } catch (Exception e2) {
                }
            }
        }
        return null;
    }

在onCreateView:

      try {
        FetchGPS fetchCordinates = new FetchGPS();
        fetchCordinates.execute();
    } catch (Exception e){}

问题:在GPS和MobData激活20秒后,我得到0.0和0.0

1 个答案:

答案 0 :(得分:1)

  • AsyncTask子类中使用静态不是最佳做法
  • 使用onPostExecute()告诉您后台任务何时完成
  • getActivity()调用doInBackground()不是最佳做法

试试这个:

public class FetchGPS extends AsyncTask<Void, Void, Double[]> {

    private static final String TAG = "FetchGPS";

    private LocationManager mLocationManager;

    public FetchGPS(Context context) {
        mLocationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    protected Double[] doInBackground(Void... params) {

        Double[] coords = null;

        try {
            Location location = mLocationManager
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            coords = new Double[2];
            coords[0] = location.getLatitude();
            coords[1] = location.getLongitude();
        } catch (Exception e) {
            Log.e(TAG, "could not get coordinates", e);
        }

        return coords;
    }
}

onCreateView()

FetchGPS fetchCordinates = new FetchGPS(this) {

    @Override
    protected void onPostExecute(Double[] result) {

        if (result != null) {
            double latitude = result[0];
            double longitude = result[1];

            // have coordinates, continue on UI thread
        } else {
            // error occurred
        }
    }

};

fetchCordinates.execute();

注意:覆盖onPostExecute()我所做的事情,在onCreateView()范围内也不是很好的做法,我只是为了这个例子。