為什麼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());
}
}
// ……
}