LocationListener InSide AsyncTask

发布于 2024-11-25 22:15:42 字数 2699 浏览 0 评论 0原文

您好,我是 Android 编程新手,目前正在开发一个应用程序,该应用程序使用位置管理器来获取用户位置并在地图上放置标记。我正在尝试使用 AsyncTask 来运行 LocationListener 并在用户位置更改时不断更新标记。 这是我正在上的课...

public class IncidentActivity extends MapActivity{


   public void onCreate(Bundle savedInstanceState){
       super.onCreate(savedInstanceState);
       this.setContentView(R.layout.incidentactivity);

       mapView = (MapView)findViewById(R.id.mapView);
       mapView.setBuiltInZoomControls(true);   
       mapView.setTraffic(true);


        mapController = mapView.getController();
        String coordinates[] = {"-26.167004","27.965505"};
        double lat = Double.parseDouble(coordinates[0]);
        double lng = Double.parseDouble(coordinates[1]);
        geoPoint = new GeoPoint((int)(lat*1E6), (int)(lng*1E6));
        mapController.animateTo(geoPoint);
        mapController.setZoom(16);
        mapView.invalidate();

         new MyLocationAsyncTask().execute();

   }



      private class MyLocationAsyncTask extends AsyncTask<Void, Location, Void> implements LocationListener{
        private  double latLocation;
        private Location l;

        //location management variables to track and maintain user location
        protected LocationManager locationManager;
        protected LocationListener locationListener;

        @Override
        protected Void doInBackground(Void... arg0) {
            Looper.prepare();
              locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
              locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener);

              this.publishProgress(l);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            super.onPostExecute(result);
        }

        @Override
        protected void onProgressUpdate(Location... values) {

            super.onProgressUpdate(values);
        }

        //this method is never executed i dont know why...?
        public void onLocationChanged(Location location) {
            if (location != null){
                latLocation = location.getLatitude(); 
                Toast.makeText(getBaseContext(), " Your latLocation :" + latLocation, Toast.LENGTH_LONG).show();
                //Log.d("Your Location", ""+latLocation);
            }
        }

        public void onProviderDisabled(String provider) {


        }

        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }


      }


}

Hi I am New to android programming and currently developing an application that uses location manager to get user location and place a marker on a map. i am attempting to use AsyncTask to run the LocationListener and Constantly update the marker when the user location has changed.
this is the class i am working on...

public class IncidentActivity extends MapActivity{


   public void onCreate(Bundle savedInstanceState){
       super.onCreate(savedInstanceState);
       this.setContentView(R.layout.incidentactivity);

       mapView = (MapView)findViewById(R.id.mapView);
       mapView.setBuiltInZoomControls(true);   
       mapView.setTraffic(true);


        mapController = mapView.getController();
        String coordinates[] = {"-26.167004","27.965505"};
        double lat = Double.parseDouble(coordinates[0]);
        double lng = Double.parseDouble(coordinates[1]);
        geoPoint = new GeoPoint((int)(lat*1E6), (int)(lng*1E6));
        mapController.animateTo(geoPoint);
        mapController.setZoom(16);
        mapView.invalidate();

         new MyLocationAsyncTask().execute();

   }



      private class MyLocationAsyncTask extends AsyncTask<Void, Location, Void> implements LocationListener{
        private  double latLocation;
        private Location l;

        //location management variables to track and maintain user location
        protected LocationManager locationManager;
        protected LocationListener locationListener;

        @Override
        protected Void doInBackground(Void... arg0) {
            Looper.prepare();
              locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
              locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener);

              this.publishProgress(l);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            super.onPostExecute(result);
        }

        @Override
        protected void onProgressUpdate(Location... values) {

            super.onProgressUpdate(values);
        }

        //this method is never executed i dont know why...?
        public void onLocationChanged(Location location) {
            if (location != null){
                latLocation = location.getLatitude(); 
                Toast.makeText(getBaseContext(), " Your latLocation :" + latLocation, Toast.LENGTH_LONG).show();
                //Log.d("Your Location", ""+latLocation);
            }
        }

        public void onProviderDisabled(String provider) {


        }

        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }


      }


}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笔芯 2024-12-02 22:15:42

我刚刚实现了这样的AsyncTask

class GetPositionTask extends AsyncTask<Void, Void, Location> implements LocationListener
{
    final long TWO_MINUTES = 2*60*1000;
    private Location location;
    private LocationManager lm;

    protected void onPreExecute()
    {
        // Configure location manager - I'm using just the network provider in this example
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
        nearProgress.setVisibility(View.VISIBLE);
    }

    protected Location doInBackground(Void... params)
    {
        // Try to use the last known position
        Location lastLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        // If it's too old, get a new one by location manager
        if (System.currentTimeMillis() - lastLocation.getTime() > TWO_MINUTES)
        {
            while (location == null)
                try { Thread.sleep(100); } catch (Exception ex) {}

            return location;
        }

        return lastLocation;
    }

    protected void onPostExecute(Location location)
    {
        nearProgress.setVisibility(View.GONE);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.removeUpdates(this);

        // HERE USE THE LOCATION
    }

    @Override
    public void onLocationChanged(Location newLocation)
    {
        location = newLocation;
    }

    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}
}

I've just implemented such AsyncTask:

class GetPositionTask extends AsyncTask<Void, Void, Location> implements LocationListener
{
    final long TWO_MINUTES = 2*60*1000;
    private Location location;
    private LocationManager lm;

    protected void onPreExecute()
    {
        // Configure location manager - I'm using just the network provider in this example
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
        nearProgress.setVisibility(View.VISIBLE);
    }

    protected Location doInBackground(Void... params)
    {
        // Try to use the last known position
        Location lastLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        // If it's too old, get a new one by location manager
        if (System.currentTimeMillis() - lastLocation.getTime() > TWO_MINUTES)
        {
            while (location == null)
                try { Thread.sleep(100); } catch (Exception ex) {}

            return location;
        }

        return lastLocation;
    }

    protected void onPostExecute(Location location)
    {
        nearProgress.setVisibility(View.GONE);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.removeUpdates(this);

        // HERE USE THE LOCATION
    }

    @Override
    public void onLocationChanged(Location newLocation)
    {
        location = newLocation;
    }

    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}
}
瑕疵 2024-12-02 22:15:42

根据我的阅读和尝试,您不能在 ASyncTask 内使用循环器(位置侦听器需要它)。 点击此处

实际上这意味着两个线程模型不兼容,所以你不能
一起使用这些。 Looper 希望拥有您关联的线程
它与,而 AsyncTask 拥有它为您创建的线程,以便在
背景。因此它们相互冲突,不能一起使用。

Dianne Hackborn 建议使用 HandlerThread,但我成功地让我的线程在 IntentService 内部工作。我承认我的代码仍然有点hack。

From what I have read and tried, you cannot use a looper (which is needed by the locationlistener), inside an ASyncTask. Click Here

Actually it mean the two threading models are not compatible, so you can't
use these together. Looper expects to to own the thread that you associate
it with, while AsyncTask owns the thread it creates for you to run in the
background. They thus conflict with each other, and can't be used together.

Dianne Hackborn suggested using a HandlerThread, but I succeeded in getting mine to work inside of an IntentService. I will admit that my code is still a bit of a hack.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文