为什么location一直为NULL呢?由与是空
double lat = loc.getLatitude(); //径纬度也就得不到了
double lng = loc.getLongitude();
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider); //为null!!!
以下是取得卫星数,可以正常工作
public void onGpsStatusChanged(int event) { // GPS状态变化时的回调,如卫星数
LocationManager locationManager = (LocationManager) GpsActivity.this.getSystemService(Context.LOCATION_SERVICE);
GpsStatus status = locationManager.getGpsStatus(null); //取当前状态
String satelliteInfo = updateGpsStatus(event, status);
myTextView.setText(satelliteInfo);//正常,显示:搜索到卫星个数:16
}
};
private String updateGpsStatus(int event, GpsStatus status) {
StringBuilder sb2 = new StringBuilder("");
if (status == null) {
sb2.append("搜索到卫星个数:" +0);
} else if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
int maxSatellites = status.getMaxSatellites();
Iterator<GpsSatellite> it = status.getSatellites().iterator();
numSatelliteList.clear();
int count = 0;
while (it.hasNext() && count <= maxSatellites) {
GpsSatellite s = it.next();
numSatelliteList.add(s);
count++;
}
sb2.append("搜索到卫星个数:" + numSatelliteList.size());
}
return sb2.toString();
}
在AVD上,这也许是好的~因为可以直接send latitiude...
谁有真机能定位的demo,室内能测最好,只需输出当前径纬度既可,感激不尽~
getLastKnownLocation()
只能返回最近的GPS方位,你需要实现一个LocationListener,使用 LocationManager#requestLocationUpdates()获得新位置
基本实现:
public class Example extends Activity implements LocationListener {
LocationManager mLocationManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
// 对最近的位置方位进行操作
// 或者等待更新
}
else {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
}
}
// ……
}
如果location为null的话 那很有可能是手机没有打开使用无线网络 在位置那里 还有可能是系统被阉割了 不过gps我没试过
可以参考这个Guide,
通过一个LocationListener去获取。
你的这种方式会阻塞的,而且获取不到。
你试试以下代码:
LocationManager locationManager = (LocationManager) this.getSystemService(MainActivity.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
最后你提取location的对应值就OK了。