【问题标题】:getLastKnownLocation() returns null using GPS_PROVIDERgetLastKnownLocation() 使用 GPS_PROVIDER 返回 null
【发布时间】:2012-06-19 03:34:36
【问题描述】:

我正在编写一个小测试程序来掌握 Android GPS 的窍门,看看电池对学校项目的影响。我只是想让我的设备通过打印出最后检测到的已知位置的纬度来检测我的位置。但是位置总是在 onResume() 回调中返回 null。

非常感谢任何帮助。

TextView Updates;
long start = -1;
long battStart = -1;
long stop = -1;
PowerManager.WakeLock wl;
LocationManager locationManager; 
LocationListener locationListener;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Updates = (TextView) findViewById(R.id.textView);
    Updates.append("\n onCreate()");

    batteryLevel();
    start = System.currentTimeMillis(); 

    locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
          // Called when a new location is found by the network location provider.
          Updates.append("\n Found a place! "+location.getLatitude()+","+location.getLongitude());
        }
        public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {
            Updates.append("yes"+provider);
        }
        public void onProviderDisabled(String provider) {
            Updates.append("No"+provider);
        }
    }; 
}

protected void onStart() {
    super.onStart();
    Updates.append("\n onStart()");

    // Set up a wake lock 
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    this.wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag2");
    this.wl.acquire();

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}


protected void onResume() {
    super.onResume();
    batteryLevel();
    Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (loc != null) {
        Updates.append(String.valueOf(loc.getLatitude()));
    } else {
        Updates.append("loc is null");
    }
}

【问题讨论】:

    标签: android gps


    【解决方案1】:

    我想通了!

    原来,我只好出去了 :)

    【讨论】:

      【解决方案2】:

      如果 GPS 被禁用,它将始终返回 null。请参阅 Android 文档以获取 LocationManager.getLastKnownLocation

      【讨论】:

        【解决方案3】:

        在这种情况下,您应该使用 LocationListener。因为它可能会发生,您可能无法从 getLastKnownLocation() 获取位置。

        只需调用 requestLocationUpdates 即可在 LocationListener 中获得回调

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-11-06
          • 2013-12-24
          • 2012-05-28
          • 1970-01-01
          • 2015-08-20
          相关资源
          最近更新 更多