所以我使用getLastKnownLocation方法获取设备的Location loc,但除非有GPS修复,否则返回null。有没有办法延迟执行getLastKnownLocation,直到GPS有一个有效的位置提供?
package test.example;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class testGPS extends Activity
{
private LocationManager lm;
private LocationListener locationListener;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
//---use the LocationManager class to obtain GPS locations---
lm = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
locationListener);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
tv.setText("Hello, lat is " + loc.getLatitude() + " lon is " + loc.getLongitude());
setContentView(tv);
} else {
tv.setText("Hello, loc is null :(");
setContentView(tv);
}
}
private class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc) {
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
}
}
答案 0 :(得分:1)
您误解了Android中的位置工作方式。除非GPS有修复,否则getLastKnownLocation()不提供null,如果没有先前已知的位置,则返回null - 该位置不必来自GPS(可能来自wifi或移动网络)并调用该方法不指示位置框架返回新位置。
在完全阅读并理解此页面后,您需要重新开始: http://developer.android.com/guide/topics/location/obtaining-user-location.html
它包含处理Android中位置所需的一切,您需要一个适合您应用程序需求的框架。如果您希望该位置保持不变(以减少GPS的使用),那么您可以将位置保存到首选项,和/或启用网络位置发送(不是那么准确,但通常更快)。对于某些应用,您可能希望快速获取一个粗略的位置(使用最后一个或网络位置提供商),然后在准确的GPS位置到达时更新它。但您使用的方法因app而异。