【问题标题】:Getting coordinates explicitly from GPS provider从 GPS 提供商明确获取坐标
【发布时间】:2013-12-10 13:51:55
【问题描述】:

我想实现一些我认为很简单的事情,但现在我最终有点困惑。 我想通过这种方式获取用户的坐标

  • 有 GPS 供应商吗?
    • 如果是,从 gps 获取坐标
    • 如果有网络提供商,则从那里获取它们

我同时使用了 locationManager 和 onLocationChange(),以及带有 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();

【问题讨论】:

  • 您需要显示更多代码。不知何故,您的“是否有 GPS 提供商”请求得到“否”,即使您认为它应该是“是”。也许您的应用程序不允许访问位置服务(隐私?)。
  • 好的,我现在就发布代码。我在清单中拥有所有必要的权限,我还检查了是否有可用的 gps 提供程序,但它返回的位置为 null

标签: android gps


【解决方案1】:

这里是找到最佳可用提供程序的完整代码,无论是gps 还是network,并显示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.
}
}

我已经在 cmets 中解释了很多,但是如果您仍然不明白,请随时提问。

【讨论】:

  • GPS 可能需要一段时间才能锁定您的位置。您可以使用网络检查您是否获得任何坐标。当 gps 获取位置时,您可以使用 log 发布日志。这样即使需要一些时间,您也会知道自己收到了位置。
【解决方案2】:

我希望您在设备上试用它并且您已经在开放环境中试用过。在大多数情况下,直到您走出去才能获得 GPS 坐标。

【讨论】:

  • 不,我不在外面……我在办公室,这可能是问题吗?
  • 是的,当然.. 只是去露台或走出去看看你是否有任何阅读并告诉我:)
【解决方案3】:

很可能您没有位置修复,与网络位置提供程序相比,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

【讨论】:

  • 我怀疑您的设备最近是否正在使用 GPS 提供程序。你能不能出去至少尝试一次 GPS 定位(通过使用另一个应用程序 - 谷歌地图或任何其他应用程序),然后再试一次代码。
  • 我的手机是新的,但它是二手的,我将其恢复为出厂设置。如果它对你有帮助,当我只激活 gps 时,谷歌地图也不会工作
  • 是的,这正是问题所在。如果 GPS 需要几个小时才能修复 GPS,或者即使由于天气恶劣而无法修复,这并不奇怪。我建议您尝试几分钟(10-20 分钟)进行 GPS 修复,否则您的设备的 GPS 可能会出现问题。但是代码正在正常工作。请通过答案中提到的链接更好地了解位置提供者的工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-03
  • 2014-07-22
  • 2012-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多