徹底解決Android GPS沒法定位這一頑固問題

來源:互聯網
上載者:User

標籤:remote   服務   配置   最新   mil   tsp   yun   應用   選擇   

       大家去網上搜尋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節點的地址來大致定位位置,

這樣的定位方式取決於server,即取決於將基站或WIF節點資訊翻譯成位置資訊的server的能力。因為眼下大部分Android手機沒有安裝google官方的location manager庫。大陸網路也不同意。即沒有server來做這個事情,自然該方法基本上沒法實現定位。

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永遠不會被調用,你仍然沒法擷取定位資訊。

 

為什麼就沒法擷取到location呢?

         事實上在上面我已經提到了,全部上面的解決的方案都沒有解決根本問題,那就是當你在室內開發時。你的手機根本就沒法擷取位置資訊,你叫系統怎樣將位置語音總機給你的程式。

所以要從根本上解決問題,就要解決位置資訊擷取問題。剛剛也提到了,僅僅有NETWORK_PROVIDER這樣的模式才是室內地圖可靠的方式,僅僅只是因為大陸的怪怪網路,且大部分廠商也不會用google的服務,這樣的定位方式預設是沒法用的。那怎麼辦?好辦,找個替代的服務商就能夠了,百度的位置資訊sdk就能夠解決問題。

它的基本原理在上面已經提到過了,就是搜集你的wifi節點資訊和你的手機基站資訊來定位。


真正的解決方式,使用百度位置定位SDK
      SDK下載:

        http://pan.baidu.com/s/1i3xGMih

         當然大家能夠在官網下載,這樣能夠下載到最新的sdk

         http://lbsyun.baidu.com/sdk/download

     SDK使用:

1.  申請百度的服務密鑰。詳細操作步驟見官網:

      http://api.map.baidu.com/lbsapi/cloud/geosdk.htm

2.將上面下載的sdk檔案locSDK_4.1.jar複製到你項目的libs下

3.  改動AndroidManifest檔案,在該檔案中加入例如以下配置

        

        <service            android:name="com.baidu.location.f"            android:enabled="true"            android:process=":remote" >        </service>        <meta-data            android:name="com.baidu.lbsapi.API_KEY"            android:value="xxxxx " /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

              上面meta-data中value的值改為你自己的密鑰

      代碼裡調用sdk:

public class LocationUtil {private final static boolean DEBUG = true;private final static String TAG = "LocationUtil";private static LocationUtil mInstance;private BDLocation mLocation = null;private MLocation  mBaseLocation = new MLocation();public static LocationUtil getInstance(Context context) {if (mInstance == null) {mInstance = new LocationUtil(context);}return mInstance;}Context mContext;String mProvider;public BDLocationListener myListener = new MyLocationListener();private LocationClient mLocationClient;public LocationUtil(Context context) {    mLocationClient = new LocationClient(context.getApplicationContext());initParams();mLocationClient.registerLocationListener(myListener);}public void startMonitor() {if (DEBUG) Log.d(TAG, "start monitor location");if (!mLocationClient.isStarted()) {mLocationClient.start();}if (mLocationClient != null && mLocationClient.isStarted()) {mLocationClient.requestLocation();} else { Log.d("LocSDK3", "locClient is null or not started");}}public void stopMonitor() {if (DEBUG) Log.d(TAG, "stop monitor location");if (mLocationClient != null && mLocationClient.isStarted()) {mLocationClient.stop();}}public BDLocation getLocation() {if (DEBUG) Log.d(TAG, "get location");return mLocation;}public MLocation getBaseLocation() {if (DEBUG) Log.d(TAG, "get location");return mBaseLocation;}private void initParams() {LocationClientOption option = new LocationClientOption();option.setOpenGps(true);//option.setPriority(LocationClientOption.NetWorkFirst);option.setAddrType("all");//返回的定位結果包括地址資訊option.setCoorType("bd09ll");//返回的定位結果是百度經緯度,預設值gcj02option.setScanSpan(5000);//設定發起定位請求的間隔時間為5000msoption.disableCache(true);//禁止啟用緩衝定位option.setPoiNumber(5);    //最多返回POI個數   option.setPoiDistance(1000); //poi查詢距離        option.setPoiExtraInfo(true); //是否須要POI的電話和地址等具體資訊        mLocationClient.setLocOption(option);}public class MyLocationListener implements BDLocationListener {@Overridepublic void onReceiveLocation(BDLocation location) {if (location == null) {return ;}mLocation = location;mBaseLocation.latitude = mLocation.getLatitude();mBaseLocation.longitude = mLocation.getLongitude();StringBuffer sb = new StringBuffer(256);sb.append("time : ");sb.append(location.getTime());sb.append("\nerror code : ");sb.append(location.getLocType());sb.append("\nlatitude : ");sb.append(location.getLatitude());sb.append("\nlontitude : ");sb.append(location.getLongitude());sb.append("\nradius : ");sb.append(location.getRadius());sb.append("\ncity : ");sb.append(location.getCity());if (location.getLocType() == BDLocation.TypeGpsLocation){sb.append("\nspeed : ");sb.append(location.getSpeed());sb.append("\nsatellite : ");sb.append(location.getSatelliteNumber());} else if (location.getLocType() == BDLocation.TypeNetWorkLocation){sb.append("\naddr : ");sb.append(location.getAddrStr());}if (DEBUG) Log.d(TAG, "" + sb);}public void onReceivePoi(BDLocation poiLocation) {}}public class MLocation {public double latitude;public double longitude;}}

             當然別忘了在setting裡將gps定位開啟

 

/********************************

* 本文來自部落格  “愛踢門”

* 轉載請標明出處:http://blog.csdn.net/itleaks

******************************************/

         

徹底解決Android GPS沒法定位這一頑固問題

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.