2012-09-10 63 views
1

我得到的android手機的位置爲:爲什麼當我更改位置時,android手機的當前位置不會改變?

android.location.Location locationA; 
      LocationManager locationManager; 
      Criteria cri = new Criteria(); 
      locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
      String tower = locationManager.getBestProvider(cri, false); 
      locationA = locationManager.getLastKnownLocation(tower); 
      if (locationA != null) { 
       // lat = (double) (locationA.getLatitude() * 1E6); 
       // longi = (double) (locationA.getLongitude() * 1E6); 
       double lat = locationA.getLatitude(); 
       double longi = locationA.getLongitude(); 

       TextView txt = (TextView) findViewById(R.id.textView1); 
       String td = String.valueOf(lat) + "," + String.valueOf(longi); 
       txt.setText(td); 
      } 

爲什麼android手機的當前位置,當我改變位置,並再次獲得當前位置不改?

+0

那麼你正在使用哪個提供者? GPS或網絡? – Andromeda

+0

GPS和網絡(String tower = locationManager.getBestProvider(cri,false); ) – mum

回答

1

使用locationA.getTime()檢查您所在位置的時間。如果它不是最新的等待一個新的位置,然後停止。

private static Location currentLocation; 
private static Location prevLocation; 

public void yourMethod() 
{ 
    locationManager.requestLocationUpdates(provider, MIN_TIME_REQUEST, 
          MIN_DISTANCE, locationListener); 
} 

private static LocationListener locationListener = new LocationListener() { 

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

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 

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

private static void gotLocation(Location location) { 
     prevLocation = currentLocation == null ? 
       null : new Location(currentLocation); 
     currentLocation = location; 

     if (isLocationNew()) { 
      // do something 

      locationManager.removeUpdates(locationListener); 
     } 

} 

private static boolean isLocationNew() { 
    if (currentLocation == null) { 
     return false; 
    } else if (prevLocation == null) { 
     return false; 
    } else if (currentLocation.getTime() == prevLocation.getTime()) { 
     return false; 
    } else { 
     return true; 
    } 
} 
相關問題