private void getLocation(){
locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
List<String> providers = locationManager.getAllProviders();
for (String provider : providers) {
Log.e("GPS_provider: ", provider);
}
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
Log.e("Best_provider: ", bestProvider);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
Log.e("Loc_changed", ""+ location.getLatitude() + location.getLongitude());
mLocation = location;
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {
Log.e("Provider_enabled:", provider);
}
public void onProviderDisabled(String provider) {
Log.e("Provider_disabled:", provider);
}
};
// Register the listener with the Location Manager to receive location updates
try {
locationManager.requestLocationUpdates(bestProvider, 0, 0, locationListener);
mLocation = locationManager.getLastKnownLocation(bestProvider);
if (mLocation == null){
mLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Log.e("GPS network", "true");
}
} catch (SecurityException e){
Log.e("GPS problem", "GPS problem "+e.getMessage());
}
}
我試圖讀取位置做一個HTTP GET找回我以前的記錄:的Android requestLocationUpdates與GPS空
private void loadBusinesses(){
gpsMsg.setVisibility(View.INVISIBLE);
getLocation();
currentView = GEOVIEW;
businessesList.nextUrl = "null";
if (!businessesList.isEmpty()){
Log.e("businessList ","not empty");
businessesList.clear();
notifyAdapter();
}
Double latitude;
Double longitude;
try{
latitude = mLocation.getLatitude();
longitude = mLocation.getLongitude();
} catch (NullPointerException e){
Log.e("GPS", "Location unavailable");
gpsMsg.setVisibility(View.VISIBLE);
swipeContainer.setRefreshing(false);
return;
}
}
即使我檢查,如果打開GPS,當我嘗試使用GPS位置時,我總是得到空白,然後它從網絡中獲取位置。 因爲這個原因,我試圖將GPS設置設置爲「僅GPS」,並且我得到NULL,所以沒有位置。 我讀過所有其他帖子,但我一直在GPS空值。我在使用USB調試的真實設備上模擬。
有什麼想法?
我用你的建議是這樣的: 'locationManager.requestSingleUpdate(bestProvider,locListen,NULL);' 在我的locListen有: '@覆蓋 公共無效onLocationChanged(位置定位){ Log.e(「Single_loc 「,location.getLongitude()+」「+ location.getLatitude()); } 問題是,如果我使用模擬器,我必須從菜單中發送位置然後它讀取位置,但是如果我使用真實設備,它沒有任何作用,它不會投影onLocationChanged,onStatusChanged, onProviderEnabled既不是onProviderDisabled。 – exrezzo
而且我也嘗試使用Google地圖,即使我在室內也能正常工作。 – exrezzo
您是否請求訪問設備位置的權限?您應該在您的AndroidManifest中通過添加權限「ACCESS_COARSE_LOCATION」和「ACCESS_FINE_LOCATION」來完成此操作。另外,從Android 6.0開始,在調用requestSingleUpdate之前,您必須在運行時請求此權限。在這裏閱讀:https://developer.android.com/training/permissions/requesting.html –