使用异步任务中的 locationmanager 获取位置

Get the location with the locationmanager inside Async task

正如标题提到的,试图获取异步任务中的位置,但是,到目前为止,我 failed.I 得到了纬度和经度的空异常 这是我的代码。

public class AsyncLocation extends AsyncTask<String, Integer, MyLocation> {

        private Context _cntx=null; 
        AsyncLocation(Context cntx){

            _cntx= cntx;
        }

        public AsyncResponse delegate;
        MyLocation myLocation =null;

        public LocationManager mLocationManager;

        @Override
        protected MyLocation doInBackground(String... arg0) {

            Log.d("GtLocation", "ICERDE");
             mLocationManager = (LocationManager)_cntx.getSystemService(Context.LOCATION_SERVICE);
             Location location =  mLocationManager.getLastKnownLocation( LocationManager.NETWORK_PROVIDER);
           double  latitude = location.getLatitude();
           double  longitude = location.getLongitude();
             Log.d("onPreExecute", "ICERDE");
            MyLocation mylc= new MyLocation();
            mylc.Lat=latitude;
            mylc.Lng=longitude;

            return mylc;

        }

        @Override
        protected void onPostExecute(MyLocation rsp) {

            Log.d("onPostExecute", "ICERDE");
                Log.d("vvvvresponse", rsp.toString());

                Toast.makeText(_cntx,
                        "LATITUDE :" + rsp.Lat + " LONGITUDE :" + rsp.Lng,
                        Toast.LENGTH_LONG).show();
                // delegate.processFinish(rsp);
                super.onPostExecute(rsp);

    }
    }

任何帮助appriciated,谢谢

我做过类似的事情。 我通过在 OnCreate() 方法中初始化位置管理器并在 OnPostExecute() 方法中调用另一种方法来解决这个问题,该方法将我的当前位置保存到 Location 类型的变量中。

     curPos = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

之后你可以通过 curPos.getLatitude()

获得 LatLng 坐标

希望对你有所帮助