大家去網上搜尋Android定位location為null沒法定位問題,估計有一大堆文章介紹如何來解決,但是最後大家發現基本沒用。本文將從Android定位實現原理來深入分析沒法定位原因並提出真正的解決方案。在分析之前,我們肯定得先看看android官方提供的定位SDK。
預設Android GPS定位執行個體
擷取LocationManager:
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
選擇Location Provider:
Android系統存在多種provider,分別是
GPS_PROVIDER:
這個就是手機裡有GPS晶片,然後利用該晶片就能利用衛星獲得自己的位置資訊。但是在室內,GPS定位基本沒用,很難定位的到。
NETWORK_PROVIDER:
這個就是利用網路定位,通常是利用手機基站和WIFI節點的地址來大致定位位置,
這種定位方式取決於伺服器,即取決於將基站或WIF節點資訊翻譯成位置資訊的伺服器的能力。由於目前大部分Android手機沒有安裝google官方的location manager庫,大陸網路也不允許,即沒有伺服器來做這個事情,自然該方法基本上沒法實現定位。
PASSIVE_PROVIDER:
被動定位方式,這個意思也比較明顯,就是用現成的,當其他應用使用定點更新了定位資訊,系統會儲存下來,該應用接收到訊息後直接讀取就可以了。比如如果系統中已經安裝了百度地圖,高德地圖(室內可以實現精確定位),你只要使用它們定位過後,再使用這種方法在你的程式肯定是可以拿到比較精確的定位資訊。
使用者可以直接指定某一個provider
String provider = mLocationManager.getProvider(LocationManager.GPS_PROVIDER);
也可以提供配置,由系統根據使用者的配置為使用者選擇一個最接近使用者需求的provider
Criteria crite = new Criteria(); crite.setAccuracy(Crite.ACCURACY_FINE); //精度 crite.setPowerRequirement(Crite.POWER_LOW); //功耗類型選擇 String provider = mLocationManager.getBestProvider(crite, true);
擷取Location
Location location = mLocationManager.getLocation(provider);
然後你會發現,這個返回的location永遠為null,你自然沒法定位。然後網上到處是諮詢為啥獲得的location為null,同樣網路到處是解決這個問題的所謂解決方案。
所謂解決方案
網上有人說,一開始location是很有可能是null的,這是因為程式還從來沒有請求 過,只需重新請求更新location,並註冊監聽器以接收更新後的location資訊。
LocationListener locationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { longitude = location.getLongitude(); latitude = location.getLatitude(); Log.d(TAG,"Location longitude:"+ longitude +" latitude: "+ latitude ); } }; mLocationManager.requestLocationUpdates(serviceProvider, 10000, 1, this);
然後你發現onLocationChanged永遠不會被調用,你仍然沒法擷取定位資訊。