1

我正在尝试为位置创建轮询服务,该服务开始更新位置并等待 2 分钟,然后删除更新

当我尝试使用我的模拟器发送位置时,我的位置监听器似乎没有收到一个。

是因为我没有为我在线程中创建的 looper 实现处理程序吗?

或者因为我的线程休眠所以我没有收到任何位置

package android.co.in;

import android.graphics.Canvas;
import android.os.Looper;
import android.view.SurfaceHolder;

public class customThread extends Thread {

boolean stop;
boolean run;
customThread()
{   
    BounceLogger.logIt(this, "Constructor()");
    stop=false;
    run=true;
}
@Override
public void run()
{
  Looper.prepare();
  BounceLogger.logIt(this, "run()");
  while(!stop)
  {
      while(run)
      {
        updateThread(); 
      }

      try 
      {
          wait();
      } 
      catch (InterruptedException e) 
      {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }

  }
  Looper.loop();
}   

//derived class should overide this function
public void updateThread()
{


}


public void runThread()
{  
  start();
}

public void stopThread()
{
    stop=true;
}

public void pauseThread()
{
    run=false;
    BounceLogger.logIt(this,"calling wait on worker thread");
}

public void resumeThread()
{
    BounceLogger.logIt(this,"calling notify on worker thread");
    run=true;
    notify();       
}


}

//responsible for all location related queries
public class UserLocationManager extends customThread{

boolean locationFound;

LocationSelector locationSelector;

UserLocationManager(BuddiesAroundActivity activity)
{
    super();
    locationFound=false;
    locationSelector=LocationSelector.getLocationSelector(activity);
}

Location GetUserLocation()
{
    queryUserLocation();
    return locationSelector.getLastKnownLocation();
}

@Override
public void updateThread()
{
    locationSelector.startListening();
    try {
        Thread.sleep(200000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    locationSelector.stopListening();
}

void queryUserLocation()
{       
    runThread();    
}


}

package android.co.in;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class LocationSelector 
{

private static LocationSelector locationSelector=null;
private static final int TWO_MINUTES = 1000 * 60 * 2;
LocationManager locationManager;
LocationListener locationListener;
Location lastKnownLocation;

LocationSelector()
{
    Intialize();
}

LocationSelector(BuddiesAroundActivity activity)
{
    Intialize();
    locationManager=
       (LocationManager)activity.getSystemService(Context.LOCATION_SERVICE);
}

static LocationSelector getLocationSelector(BuddiesAroundActivity activity)
{
    if(locationSelector==null)
        locationSelector = new LocationSelector(activity);

    return locationSelector;    
}

void startListening()
{
    if(locationManager!=null)
    {
        BounceLogger.logIt(this, "started listening on location updates");

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,100,     locationListener);
              locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000,100, locationListener);
    }
}

public void stopListening()
{
    BounceLogger.logIt(this, "stopped listening on location updates");
    locationManager.removeUpdates(locationListener);
}


private void Intialize() 
{
    lastKnownLocation=null;
    // TODO Auto-generated method stub
    locationListener=new LocationListener() {
        public void onLocationChanged(Location current) 
        {
          // Called when a new location is found by the network location     provider.
            BounceLogger.logIt(this,"recived a location"+current.getLatitude()+":"+current.getLongitude());
            if(lastKnownLocation==null)
            {
                lastKnownLocation=current;
            }
            getBestLocation(lastKnownLocation,current);

        }

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

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}

      };

}

private float getDistanceBetweenLocations(Location a,Location b)
{
    float distance =a.distanceTo(b);     
    return distance;     
}

private double getAngleBetweenLocations(Location origin,Location destination)
{
     double angle=0.0f;
     double longDiff;
     double latDiff;

     longDiff=destination.getLongitude()-origin.getLongitude();
     latDiff=destination.getLatitude()-origin.getLatitude();

     angle=Math.atan2(longDiff,latDiff);         
     return angle; 
 }

Location getLastKnownLocation()
{
    return lastKnownLocation;
}

Location getBestLocation(Location old,Location current)
{
    if(old ==null)
        return current;

    //check time
    long timeDelta = current.getTime() - old.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    int useCurrentLocationByTime=0;
    if(isSignificantlyNewer)
    {
        useCurrentLocationByTime++;
    }

    //check for accuracy
    int useCurrentLocationByAccuracy=0;
    if(old.getAccuracy() < current.getAccuracy())
    {
        useCurrentLocationByAccuracy++;
    }

    //check for provider this is blunt but u might want give priority to providers and then decide
    int useCurrentLocationByProvider=0;
    if(old.getProvider().equals(current.getProvider()))
    {
        useCurrentLocationByProvider++;
    }

    int points=useCurrentLocationByTime+useCurrentLocationByAccuracy+useCurrentLocationByProvider;

    if(points > 1.5)
    {
        return current;     
    }

    return old;     
}

}

4

2 回答 2

0

在您的 updateThread 中,您启动对 Location 的请求,然后将线程 tp sleep 200 秒,这使得无法接收新位置。线程一醒来,您就删除位置更新请求。

您需要重新设计代码,使 Location Listner 在不同的线程中运行,或者更好的是,您使用 handler.post() 方法在 200 秒后运行可运行的方法,这将停止位置侦听器并避免使用线程为了那个原因。

--已编辑--

你应该做这样的事情:

Handler handler = new Handler();
startLocationListener(); //in this method you only add the listener for onLocationsChange(). No threads needed.
handler.postDelayed(rStopLocationListener, 200000); //the runnable rStopLocationListener will run in 200 seconds

//define rStopLocationListener
private Runnable rStopLocationListener = new Runnable() {
  public void run() {
          stopLocationListener(); //in this method you only remove the listener for onLocationsChange(). No threads needed.
  }
};
于 2012-10-04T19:14:47.740 回答
0

包android.co.in;

import android.graphics.Canvas;
import android.os.Looper;
import android.view.SurfaceHolder;

public class customThread extends Thread {

boolean stop;
boolean run;
customThread()
{   
    BounceLogger.logIt(this, "Constructor()");
    stop=false;
    run=true;
}
    @Override
    public void run()
    {
  //Looper.prepare();
  BounceLogger.logIt(this, "run()");
  while(!stop)
  {
      while(run)
      {
        updateThread(); 
      }

      try 
      {
          wait();
      } 
      catch (InterruptedException e) 
      {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }

  }
  //Looper.loop();
    }   

    //derived class should overide this function
   public void updateThread()
  {


  }


  public void runThread()
  {  
  start();
  }

  public void stopThread()
{
    stop=true;
}

  public void pauseThread()
{
    run=false;
    BounceLogger.logIt(this,"calling wait on worker thread");
}

  public void resumeThread()
{
    BounceLogger.logIt(this,"calling notify on worker thread");
    run=true;
    notify();       
}


   }

  class customLooperThread extends Thread {

boolean stop;
boolean run;
customLooperThread()
{   
    BounceLogger.logIt(this, "Constructor()");
    stop=false;
    run=true;
}
   @Override
   public void run()
   {
  Looper.prepare();
  BounceLogger.logIt(this, "run()");
  while(!stop)
  {
      while(run)
      {
        updateThread(); 
      }

      try 
      {
          wait();
      } 
      catch (InterruptedException e) 
      {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }

  }
  Looper.loop();
  } 

   //derived class should overide this function
  public void updateThread()
  {


  }


 public void runThread()
 {  
  start();
 }

 public void stopThread()
{
    stop=true;
}

 public void pauseThread()
{
    run=false;
    BounceLogger.logIt(this,"calling wait on worker thread");
}

  public void resumeThread()
{
    BounceLogger.logIt(this,"calling notify on worker thread");
    run=true;
    notify();       
}


   }




   //responsible for all location related queries
   public class UserLocationManager extends customLooperThread{

boolean locationFound;

LocationSelector locationSelector;
Handler h;

UserLocationManager(BuddiesAroundActivity activity,Handler uiHandler)
{
    super();
    locationFound=false;
    locationSelector=LocationSelector.getLocationSelector(activity);

}

Location GetUserLocation()
{
    queryUserLocation();
    return locationSelector.getLastKnownLocation();
}

@Override
public void updateThread() 
{
    locationSelector.startListening();
    h= new Handler();
    h.postAtTime(locationSelector, 20000);
    try {
        sleep(20000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    locationSelector.stopListening();
}

void queryUserLocation()
{       
    runThread();    
}


   }



   public class LocationSelector extends customThread
   {

private static LocationSelector locationSelector=null;
private static final int TWO_MINUTES = 1000 * 60 * 2;
LocationManager locationManager;
LocationListener locationListener;
Location lastKnownLocation;

LocationSelector()
{
    Intialize();
}

LocationSelector(BuddiesAroundActivity activity)
{
    Intialize();
    locationManager= 
                 (LocationManager)activity.getSystemService(Context.LOCATION_SERVICE);
}

static LocationSelector getLocationSelector(BuddiesAroundActivity activity)
{
    if(locationSelector==null)
        locationSelector = new LocationSelector(activity);

    return locationSelector;    
}

void startListening()
{
    if(locationManager!=null)
    {
        BounceLogger.logIt(this, "started listening on location updates");

          locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,100,   
          locationListener);

      locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000,100,                   
      locationListener);
    }
}

public void stopListening()
{
    BounceLogger.logIt(this, "stopped listening on location updates");
    locationManager.removeUpdates(locationListener);
}


@Override
public void updateThread()
{
BounceLogger.logIt(this, "updateThread");
}


private void Intialize() 
{
    lastKnownLocation=null;
    // TODO Auto-generated method stub
    locationListener=new LocationListener() {
        public void onLocationChanged(Location current) 
        {
          // Called when a new location is found by the network location provider.
            BounceLogger.logIt(this,"recived a location"+current.getLatitude()+":"+current.getLongitude());
            if(lastKnownLocation==null)
            {
                lastKnownLocation=current;
            }
            getBestLocation(lastKnownLocation,current);

        }

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

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}

      };

}

private float getDistanceBetweenLocations(Location a,Location b)
{
    float distance =a.distanceTo(b);     
    return distance;     
}

private double getAngleBetweenLocations(Location origin,Location destination)
{
     double angle=0.0f;
     double longDiff;
     double latDiff;

     longDiff=destination.getLongitude()-origin.getLongitude();
     latDiff=destination.getLatitude()-origin.getLatitude();

     angle=Math.atan2(longDiff,latDiff);         
     return angle; 
 }

Location getLastKnownLocation()
{
    return lastKnownLocation;
}

Location getBestLocation(Location old,Location current)
{
    if(old ==null)
        return current;

    //check time
    long timeDelta = current.getTime() - old.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    int useCurrentLocationByTime=0;
    if(isSignificantlyNewer)
    {
        useCurrentLocationByTime++;
    }

    //check for accuracy
    int useCurrentLocationByAccuracy=0;
    if(old.getAccuracy() < current.getAccuracy())
    {
        useCurrentLocationByAccuracy++;
    }

    //check for provider this is blunt but u might want give priority to providers and then decide
    int useCurrentLocationByProvider=0;
    if(old.getProvider().equals(current.getProvider()))
    {
        useCurrentLocationByProvider++;
    }

    int points=useCurrentLocationByTime+useCurrentLocationByAccuracy+useCurrentLocationByProvider;

    if(points > 1.5)
    {
        return current;     
    }

    return old;     
}

}

于 2012-10-06T18:12:52.993 回答