【问题标题】:Getting GPS data from Android Phone从 Android 手机获取 GPS 数据
【发布时间】:2013-03-27 22:23:25
【问题描述】:

我尝试获取 gps 数据。但是 gps 数据返回空值。当我查看时,以下“位置”返回 null,所以我无法获取 gps 数据。
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

我的代码如下;

    protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager)           mContext.getSystemService(LOCATION_SERVICE);

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

        // getting network status
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!isGPSEnabled)
        {

        }
        else if (!isGPSEnabled && !isNetworkEnabled) 
        {
                        } 
        else 
        {
            this.canGetLocation = true;

            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {

                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }

我等待你的帮助。谢谢

【问题讨论】:

  • 我发现如果用户有一段时间没有激活/使用位置源,函数 getLastKnownLocation() 有时会返回 null。最好像你一样检查。如果为null,则需要等待下一次位置更新
  • 或者设置一个 requestSingleUpdate 或者 requestLocationUpdates 来自己开启 GPS。
  • 如果提供者当前被禁用,则返回 null。我使用 GPS_PROVIDER。如何启用?

标签: android gps


【解决方案1】:

您是否在清单中设置了这些?

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

【讨论】:

    【解决方案2】:

    我改成下面的代码,然后就成功了。

    String bestProvider = locationManager.getBestProvider(criteria, false);
                    
    locationManager.requestLocationUpdates(bestProvider, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
        if (locationManager != null) {
            location = locationManager.getLastKnownLocation(bestProvider);
            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多