2013-12-09 35 views
1

我使用此代碼來獲取用戶的地理定位我的GPS供應商已啓用,但我得到空位置仍然

public Location getLocation() { 

     Location location = null; 
     double lat; 
     double lng; 
     try { 
      LocationManager mLocationManager = (LocationManager) con.getSystemService(LOCATION_SERVICE); 

      // getting GPS status 
      boolean isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // getting network status 
      boolean isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 


      if (!isGPSEnabled && !isNetworkEnabled) { 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       startActivity(intent); 
      } else { 
       // First get location from Network Provider 
       if (isNetworkEnabled) { 
        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); 
        Log.d("Network", "Network"); 
        if (mLocationManager != null) { 
         location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         if (location != null) { 
          lat = location.getLatitude(); 
          lng = location.getLongitude(); 
          System.out.println(lat); 
         } 
        } 
       } 
       //get the location by gps 
       if (isGPSEnabled) { 
         mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, this); 
         Log.d("GPS Enabled", "GPS Enabled"); 
         if (mLocationManager != null) { 
          location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          if (location != null) { 
           lat = location.getLatitude(); 
           lng = location.getLongitude(); 
           System.out.println(lat); 
          }        
         } 
       } 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 



     return location; 
    } 

的,這是我所得到的:

網絡 39.68967 GPS功能的 (無)

爲什麼啓用GPS,我仍然無法從GPS提供商提供的座標,我不能明白其中的道理

+1

因爲你沒有一個緩存的最後一個位置,如果啓動谷歌地圖或使用您的位置是你可能會得到一個,那麼你可以再次運行你的應用程序 – tyczj

+0

我did..The同樣的事情發生 – Libathos

+0

你無論如何應該使用新的位置API http://developer.android.com/google/play-services/location.html – tyczj

回答

3

我剛剛完成了一個示例項目,以瞭解Location Services的用法。我只是發佈我的代碼,隨時可以使用它來滿足您的需求並瞭解Location Services的工作原理。

public class DSLVFragmentClicks extends Activity implements LocationListener { 
private final int BESTAVAILABLEPROVIDERCODE = 1; 
private final int BESTPROVIDERCODE = 2; 
LocationManager locationManager; 
String bestProvider; 
String bestAvailableProvider; 

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == BESTPROVIDERCODE) { 
     if (resultCode!= Activity.RESULT_OK || locationManager.isProviderEnabled(bestProvider)) { 
      Toast.makeText(getActivity(), "Error! Location Service " + bestProvider + " not Enabled", Toast.LENGTH_LONG).show(); 

     } else { 
      getLocation(bestProvider); 
     } 
    } else { 
     if (resultCode!= Activity.RESULT_OK || locationManager.isProviderEnabled(bestAvailableProvider)) { 
      Toast.makeText(getActivity(), "Error! Location Service " + bestAvailableProvider + " not Enabled", Toast.LENGTH_LONG).show(); 

     } else { 
      getLocation(bestAvailableProvider); 
     } 
    } 
} 

public void getLocation(String usedLocationService) { 
    Toast.makeText(getActivity(), "getting Location", Toast.LENGTH_SHORT).show(); 
    long updateTime = 0; 
    float updateDistance = 0; 
    // finding the current location 
    locationManager.requestLocationUpdates(usedLocationService, updateTime, updateDistance, this); 

} 


@Override 
public void onCreate(Bundle savedState) { 
    super.onCreate(savedState); 
    setContentView(R.layout.main); 
    // set a Criteria specifying things you want from a particular Location Service 
      Criteria criteria = new Criteria(); 
      criteria.setSpeedRequired(false); 
      criteria.setAccuracy(Criteria.ACCURACY_FINE); 
      criteria.setCostAllowed(true); 
      criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH); 
      criteria.setAltitudeRequired(false); 

      locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); 
      // finding best provider without fulfilling the criteria 
      bestProvider = locationManager.getBestProvider(criteria, false); 
      // finding best provider which fulfills the criteria 
      bestAvailableProvider = locationManager.getBestProvider(criteria, true); 
      String toastMessage = null; 
      if (bestProvider == null) { 
       toastMessage = "NO best Provider Found"; 
      } else if (bestAvailableProvider != null && bestAvailableProvider.equals(bestAvailableProvider)) { 
       boolean enabled = locationManager.isProviderEnabled(bestAvailableProvider); 
       if (!enabled) { 
        Toast.makeText(getActivity(), " Please enable " + bestAvailableProvider + " to find your location", Toast.LENGTH_LONG).show(); 
        Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
        startActivityForResult(mainIntent, BESTAVAILABLEPROVIDERCODE); 
       } else { 
        getLocation(bestAvailableProvider); 
       } 
       toastMessage = bestAvailableProvider + " used for getting your current location"; 
      } else { 
       boolean enabled = locationManager.isProviderEnabled(bestProvider); 
       if (!enabled) { 
        Toast.makeText(getActivity(), " Please enable " + bestProvider + " to find your location", Toast.LENGTH_LONG).show(); 
        Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
        startActivityForResult(mainIntent, BESTPROVIDERCODE); 
       } else { 
        getLocation(bestProvider); 
       } 
       toastMessage = bestProvider + " is used to get your current location"; 

      } 
      Toast.makeText(getActivity(), toastMessage, Toast.LENGTH_LONG).show(); 
      return true; 
     } 
    }); 
} 

@Override 
public void onLocationChanged(Location location) { 
    Log.d("Location Found", location.getLatitude() + " " + location.getLongitude()); 
    // getting the street address from longitute and latitude 
    Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault()); 
    String addressString = "not found !!"; 
    try { 
     List<Address> addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 
     StringBuilder stringBuilder = new StringBuilder(); 
     if (addressList.size() > 0) { 
      Address address = addressList.get(0); 
      for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { 
       stringBuilder.append(address.getAddressLine(i)).append("\n"); 
       stringBuilder.append(address.getLocality()).append("\n"); 
       stringBuilder.append(address.getPostalCode()).append("\n"); 
       stringBuilder.append(address.getCountryName()).append("\n"); 
      } 

      addressString = stringBuilder.toString(); 
      locationManager.removeUpdates(this); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 
    } 
    Toast.makeText(getActivity(), " Your Location is " + addressString, Toast.LENGTH_LONG).show(); 
} 

@Override 
public void onStatusChanged(String s, int i, Bundle bundle) { 
    //To change body of implemented methods use File | Settings | File Templates. 
} 

@Override 
public void onProviderEnabled(String s) { 
    //To change body of implemented methods use File | Settings | File Templates. 
} 

@Override 
public void onProviderDisabled(String s) { 
    //To change body of implemented methods use File | Settings | File Templates. 
} 
} 

如果你不明白它的任何部分,然後隨意問。

2
// Use LocationManager.NETWORK_PROVIDER instead of GPS_PROVIDER. 

public Location getLocation(){ 
    try{ 
    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
    }catch (Exception e) { 
     e.printStackTrace(); 
    } 
    if(locationManager != null){ 
     locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); 
     location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
     latitude = location.getLatitude(); 
    longitude = location.getLongitude(); 
    } 
    return location; 
} 
相關問題