2013-12-10 75 views
1

我想要實現某些我雖然很簡單但現在最終變得有點困惑的東西。 我想以這種方式獲得用戶的座標從GPS提供商明確獲取座標

  • 是否有GPS提供商?
    • 如果是的話,得到的GPS
    • 否則座標,如果有一個網絡提供商從那裏

讓他們我同時使用locationManageronLocationChange(),並與locationClient新的API,但我無法從我的設備的GPS獲取座標,只能從網絡獲取。

這是一個與locationManager

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
// Define the criteria how to select the locatioin provider -> use default 
Criteria criteria = new Criteria(); 
String provider = locationManager.getBestProvider(criteria, false); 
Location location = locationManager.getLastKnownLocation(provider); 

// Initialize the location fields 
if (location != null) { 
    System.out.println("Provider " + provider + " has been selected."); 
    // new AlertDialog.Builder(v.getContext()).setMessage("Provider " + provider + " has been selected.").show(); 
    onLocationChanged(location); 
    System.out.println(location.getLatitude()); 
    Intent intent = new Intent(getApplicationContext(),DriveMeActivity.class); 
    intent.putExtra("monument", monument); 
    intent.putExtra("latitude", location.getLatitude()); 
    intent.putExtra("longitude",location.getLongitude()); 
    startActivity(intent); 
} else { 
    new AlertDialog.Builder(con).setMessage("Location not available").show(); 
    System.out.println("Location not available"); 
    System.out.println("Location not available"); 
} 

,這是一個與locationClient

GooglePlayServicesUtil.isGooglePlayServicesAvailable(v.getContext()) 
if(mLocationClient.getLastLocation()!=null) 
    Toast.makeText(getApplicationContext(), 
     mLocationClient.getLastLocation().getLongitude()+ "|" + 
     mLocationClient.getLastLocation().getLatitude() , 
     Toast.LENGTH_SHORT).show(); 
+0

您需要展示更多代碼。不知何故,即使您認爲它應該是「是」,您的「有沒有GPS提供商」的請求也會變得「不」。也許你的應用程序不允許訪問定位服務(隱私?)。 – Floris

+0

好吧,我現在將發佈代碼。我在清單中擁有所有必要的權限,如果有可用的gps提供程序,我也檢查過它,但它返回的位置爲空 – Libathos

+0

http://stackoverflow.com/a/16393534/2345913 – CRUSADER

回答

2

這裏是完整的代碼,以找到最好的供應商gpsnetwork以及是否顯示settings menu啓用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 (requestCode != Activity.RESULT_OK || locationManager.isProviderEnabled(bestProvider)) { 
      Toast.makeText(getActivity(), "Error! Location Service " + bestProvider + " not Enabled", Toast.LENGTH_LONG).show(); 

     } else { 
      getLocation(bestProvider); 
     } 
    } else { 
     if (requestCode != 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(); 
// show settings menu to start gps or network location service 
        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. 
} 
} 

我已經在評論中解釋了很多,但是如果你還是不明白的話,請隨時詢問。

+0

GPS可能需要一段時間才能鎖定你的位置。您可以使用網絡來檢查您是否獲得任何座標。當gps獲取位置時,您可以使用日誌發佈日誌。這樣你就會知道你收到了一個位置,即使需要一段時間。 –

1

我希望你嘗試它的設備上並且已在公開嘗試過了。在大多數情況下,你不會獲得gps座標,直到你走出去。

+0

不,我是不是公開的......我在辦公室,這可能是問題嗎? – Libathos

+0

是的絕對..只是去露臺或走出去打開,並檢查如果你有任何閱讀,並讓我知道:) –

1

很可能你沒有定位和GPS locationProvider比網絡位置提供商需要時間來獲取定位。

你能做什麼是你可以使用最後一次已知的位置修復。

String locationProvider = LocationManager.GPS_PROVIDER; 
// Or use LocationManager.NETWORK_PROVIDER 
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); 

但進一步的問題是,你可能有舊的位置修復和網絡提供商可以爲您提供更好的位置。

Android有非常好的文檔和示例代碼來找到最有名的位置。 http://developer.android.com/guide/topics/location/strategies.html

+0

沒有仍然,它返回空..... – Libathos

+0

我懷疑,如果GPS提供商最近正在使用你的設備。你能否出去嘗試至少獲得一次GPS定位(使用另一個應用谷歌地圖或任何其他應用程序),然後再次嘗試代碼。 –

+0

我的手機是新的,但它是一個使用的,我恢復到出廠設置。如果它可以幫助你,谷歌地圖也不會工作,當我只有GPS激活 – Libathos