2013-12-10 41 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