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

Android Location: simple one-time GPS fetch using AsyncTask

我尝试用最后已知位置更新静态变量纬度和经度。

Class:

    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

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

试试这个:

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

注意:在 onCreateView() 之内覆盖 onPostExecute() 也不是很好的做法,我只是为了示例而这样做。