4
我對固定位置有問題。我使用getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
但始終返回空,我已在您的AndroidManifest.xml
中設置權限。getLastKnownLocation方法始終返回空值
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
並在設置 - >位置和安全 - >位置通過網絡啓用。
TextView locationShow = (TextView) this.findViewById(R.id.location);
double latitude = 0.0, longitude = 0.0;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
else {
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (location != null) {
Log.i("SuperMap", "Location changed : Lat: " + location.getLatitude() + " Lng: " +
location.getLongitude());
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0,
locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
locationShow.setText("經度:" + latitude + "緯度:" + longitude);
我發現其他應用程序可以正確顯示位置,所以也許我的代碼有問題。
謝謝,那麼我該如何修改我的代碼才能獲得有效的修復程序。幾分鐘的等待時間很長。我可以使用onLocationChanged來獲取它嗎? –
當然,您必須使用位置偵聽器的onLocationChanged方法。獲取有效的修復需要時間(幾分鐘) – Reno
public void onLocationChanged(Location location){ if(location!= null)Log.i(「SuperMap」,「Location changed:Lat:」+ location.getLatitude() +「Lng:」+ location.getLongitude()); latitude = location.getLatitude(); longitude = location.getLongitude(); locationShow.setText(「經度:」+緯度+「緯度:」+經度); } } 我已經等了超過10分鐘,但仍然沒有得到有效的修復,很奇怪。 –