關於如何在安卓的百度地圖開發裡面簡單實現持續定位

来源:http://www.cnblogs.com/ztjloveshanshan/archive/2017/01/04/6250461.html
-Advertisement-
Play Games

這幾天自己研究了關於地手機上面開發安卓地圖的問題,發現百度官方示例demo講解百度持續定位方面還是講解的有些不清楚,本人研究了幾次之後將其弄得更詳細以便於讓各位方便學習,有不足之處請在評論區指出,官方示例的網址是:http://lbsyun.baidu.com/index.php?title=and ...


這幾天自己研究了關於地手機上面開發安卓地圖的問題,發現百度官方示例demo講解百度持續定位方面還是講解的有些不清楚,本人研究了幾次之後將其弄得更詳細以便於讓各位方便學習,有不足之處請在評論區指出,官方示例的網址是:http://lbsyun.baidu.com/index.php?title=android-locsdk/guide/v5-0

上面的網址已經將安卓簡單配置百度地圖環境講解的很詳細了,再次不做贅述了,此外,可能會有人發現

  1 package com.example.andoridloca;
  2 
  3 import java.util.List;
  4 import java.util.Timer;
  5 import java.util.TimerTask;
  6 
  7 import android.app.Activity;
  8 import android.content.ContentValues;
  9 import android.content.Intent;
 10 import android.database.Cursor;
 11 import android.os.Bundle;
 12 import android.os.Handler;
 13 import android.os.Message;
 14 import android.text.method.ScrollingMovementMethod;
 15 import android.util.Log;
 16 import android.view.Menu;
 17 import android.view.MenuItem;
 18 import android.view.View;
 19 import android.view.View.OnClickListener;
 20 import android.widget.Button;
 21 import android.widget.TextView;
 22 import android.widget.Toast;
 23 
 24 import com.baidu.location.BDLocation;
 25 import com.baidu.location.BDLocationListener;
 26 import com.baidu.location.LocationClient;
 27 import com.baidu.location.LocationClientOption;
 28 import com.baidu.location.BDNotifyListener;//假如用到位置提醒功能,需要import該類
 29 import com.baidu.location.LocationClientOption.LocationMode;
 30 import com.baidu.location.Poi;
 31 import com.baidu.mapapi.SDKInitializer;
 32 import com.baidu.mapapi.map.MapView;
 33 
 34 public class MainActivity extends Activity implements OnClickListener{
 35     MapView mMapView = null;  
 36     public static final String TAG="mian";
 37     StringBuffer sb = new StringBuffer(256);
 38     public StringBuilder builder=new StringBuilder();
 39     private Button bt1;
 40     private TextView tv1;
 41     private DBtools DBhelper;
 42     boolean isOpenLocation=false;
 43     public LocationClient mLocationClient = null;
 44     public BDLocationListener myListener = new MyLocationListener();
 45     @Override
 46     protected void onCreate(Bundle savedInstanceState) {
 47         super.onCreate(savedInstanceState);
 48         SDKInitializer.initialize(getApplicationContext());  
 49         setContentView(R.layout.activity_main);
 50         DBhelper = new DBtools(this);    
 51         tv1=(TextView) findViewById(R.id.textView1);
 52         tv1.setMovementMethod(new ScrollingMovementMethod());
 53         bt1=(Button) findViewById(R.id.button1);
 54         bt1.setOnClickListener(this);
 55         mMapView = (MapView) findViewById(R.id.bmapView); 
 56         mLocationClient = new LocationClient(getApplicationContext());     //聲明LocationClient類
 57         mLocationClient.registerLocationListener( myListener );    //註冊監聽函數
 58         initLocation();
 59     }
 60     private void initLocation(){
 61         LocationClientOption option = new LocationClientOption();
 62         option.setLocationMode(LocationMode.Hight_Accuracy
 63 );//可選,預設高精度,設置定位模式,高精度,低功耗,僅設備
 64         option.setCoorType("bd09ll");//可選,預設gcj02,設置返回的定位結果坐標系
 65         int span=0;
 66         option.setScanSpan(span);//可選,預設0,即僅定位一次,設置發起定位請求的間隔需要大於等於1000ms才是有效的
 67         option.setIsNeedAddress(true);//可選,設置是否需要地址信息,預設不需要
 68         option.setOpenGps(true);//可選,預設false,設置是否使用gps
 69         option.setLocationNotify(true);//可選,預設false,設置是否當gps有效時按照1S1次頻率輸出GPS結果
 70         option.setIsNeedLocationDescribe(true);//可選,預設false,設置是否需要位置語義化結果,可以在BDLocation.getLocationDescribe里得到,結果類似於“在北京天安門附近”
 71         option.setIsNeedLocationPoiList(true);//可選,預設false,設置是否需要POI結果,可以在BDLocation.getPoiList里得到
 72         option.setIgnoreKillProcess(false);//可選,預設true,定位SDK內部是一個SERVICE,並放到了獨立進程,設置是否在stop的時候殺死這個進程,預設不殺死  
 73         option.SetIgnoreCacheException(false);//可選,預設false,設置是否收集CRASH信息,預設收集
 74         option.setEnableSimulateGps(false);//可選,預設false,設置是否需要過濾gps模擬結果,預設需要
 75         mLocationClient.setLocOption(option);
 76     }
 77     @Override  
 78     protected void onDestroy() {  
 79         super.onDestroy();  
 80         //在activity執行onDestroy時執行mMapView.onDestroy(),實現地圖生命周期管理  
 81         mMapView.onDestroy();  
 82     }  
 83     @Override  
 84     protected void onResume() {  
 85         super.onResume();  
 86         //在activity執行onResume時執行mMapView. onResume (),實現地圖生命周期管理  
 87         mMapView.onResume();  
 88         }  
 89     @Override  
 90     protected void onPause() {  
 91         super.onPause();  
 92         //在activity執行onPause時執行mMapView. onPause (),實現地圖生命周期管理  
 93         mMapView.onPause();  
 94         }  
 95     public class MyLocationListener implements BDLocationListener {
 96          
 97         @Override
 98         public void onReceiveLocation(BDLocation location) {
 99             //Receive Location
100             StringBuffer sb = new StringBuffer(256);
101             sb.append("time : ");
102             sb.append(location.getTime());
103             sb.append("\nerror code : ");
104             sb.append(location.getLocType());
105             sb.append("\nlatitude : ");
106             sb.append(location.getLatitude());
107             sb.append("\nlontitude : ");
108             sb.append(location.getLongitude());
109             sb.append("\nradius : ");
110             sb.append(location.getRadius());
111             if (location.getLocType() == BDLocation.TypeGpsLocation){// GPS定位結果
112                 sb.append("\nspeed : ");
113                 sb.append(location.getSpeed());// 單位:公裡每小時
114                 sb.append("\nsatellite : ");
115                 sb.append(location.getSatelliteNumber());
116                 sb.append("\nheight : ");
117                 sb.append(location.getAltitude());// 單位:米
118                 sb.append("\ndirection : ");
119                 sb.append(location.getDirection());// 單位度
120                 sb.append("\naddr : ");
121                 sb.append(location.getAddrStr());
122                 sb.append("\ndescribe : ");
123                 sb.append("gps定位成功");
124  
125             } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){// 網路定位結果
126                 sb.append("\naddr : ");
127                 sb.append(location.getAddrStr());
128                 //運營商信息
129                 sb.append("\noperationers : ");
130                 sb.append(location.getOperators());
131                 sb.append("\ndescribe : ");
132                 sb.append("網路定位成功");
133             } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 離線定位結果
134                 sb.append("\ndescribe : ");
135                 sb.append("離線定位成功,離線定位結果也是有效的");
136             } else if (location.getLocType() == BDLocation.TypeServerError) {
137                 sb.append("\ndescribe : ");
138                 sb.append("服務端網路定位失敗,可以反饋IMEI號和大體定位時間到[email protected],會有人追查原因");
139             } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
140                 sb.append("\ndescribe : ");
141                 sb.append("網路不同導致定位失敗,請檢查網路是否通暢");
142             } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
143                 sb.append("\ndescribe : ");
144                 sb.append("無法獲取有效定位依據導致定位失敗,一般是由於手機的原因,處於飛行模式下一般會造成這種結果,可以試著重啟手機");
145             }
146                 sb.append("\nlocationdescribe : ");
147                 sb.append(location.getLocationDescribe());// 位置語義化信息
148                 List<Poi> list = location.getPoiList();// POI數據
149                 if (list != null) {
150                     sb.append("\npoilist size = : ");
151                     sb.append(list.size());
152                     for (Poi p : list) {
153                     sb.append("\npoi= : ");
154                     sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
155                     }
156                 }
157             Log.i("BaiduLocationApiDem", sb.toString());
158             DBtools dbhelper=new DBtools(getApplicationContext());
159             ContentValues initialValues = new ContentValues();
160             initialValues.put("shijian",location.getTime());
161             initialValues.put("didian",location.getLatitude()+"--"+location.getLongitude());
162             dbhelper.open();
163             dbhelper.insert("path",initialValues);
164             dbhelper.close();
165             tv1.setText(sb.toString());    
166         }
167     }
168     
169     @Override
170     public void onClick(View arg0) {
171         Thread mytime=new Thread(new ThreadShow());
172             if(isOpenLocation){
173                 mLocationClient.stop();
174                 isOpenLocation=false;  
175                 
176             }
177             else{
178                 Toast.makeText(getApplicationContext(), "開啟", Toast.LENGTH_SHORT).show();        
179                 isOpenLocation=true;
180                 //mLocationClient.start();
181                 mytime.start(); 
182             }
183             
184         }
185     // handler類接收數據  
186     Handler handler = new Handler() {  
187         public void handleMessage(Message msg) {  
188             if (msg.what == 1) {  
189                 Log.i("BaiduLocationApiDem", "加以");
190                 mLocationClient.start();
191                 mLocationClient.requestLocation(); 
192             }  
193         };  
194     }; 
195      // 線程類  
196     class ThreadShow implements Runnable {  
197   
198         @Override  
199         public void run() {  
200             // TODO Auto-generated method stub  
201             while (isOpenLocation) {  
202                 try {  
203                     mLocationClient.stop();
204                     Thread.sleep(2000);  
205                     Message msg = new Message();  
206                     msg.what = 1;  
207                     handler.sendMessage(msg);  
208                    // System.out.println("send...");  
209                 } catch (Exception e) {  
210                     // TODO Auto-generated catch block  
211                     e.printStackTrace();  
212                     System.out.println("thread error...");  
213                 }  
214             }  
215         }  
216     }  
217 
218     
219     }
220     
221     
222     
223     
224     
225     
226     

這裡面關於mLocationClient.stop();mLocationClient.start();  mLocationClient.requestLocation(); 這三個函數我有必要講解一下,因為持續定位時這三個函數的配合使用很重要,官方文檔裡面解釋說mLocationClient.start()函數用於開啟定位,mLocationClient.requestLocation()函數用於主動觸發定位SDK內部定位邏輯,個人感覺差不多,兩個都會執行我的mLocationClient的所屬類裡面的邏輯代碼,可能是我的項目就這樣吧,然後是mLocationClient.stop(),此函數用於停止定位,如果持續定位的話,是需要和mLocationClient.start()函數配合使用的,具體在上面的代碼裡面有展示。

切記不要將mLocationClient.start()mLocationClient.stop()一起使用,我在網上查詢時好像是說一部原因,具體舉一個例子吧:

 

1 //某段代碼如果是這樣的話按照邏輯韓式會將mLocationClient所屬類的裡面邏輯代碼執行一遍,具體見MainAvtivity裡面的MyLocationListener類內容,但是實際上是不會執行的
2 mLocationClient.start();
3 mLocationClient.stop();

 

所以在我的MainActivity裡面我使用線程來一遍遍的執行start和stop函數,這樣就會消除剛剛說的這種效果,最後就能夠實現持續定位了。

 

在此給出我的佈局文件配合看看

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.newloca.MainActivity" >
<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="300dp">

   <com.baidu.mapapi.map.MapView  
    android:id="@+id/bmapView"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    android:clickable="true" />

</RelativeLayout>
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:scrollbars="vertical"
        android:background="#f00"
        android:text="位置信息" />
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
           >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:text="獲取位置" />
    
    </RelativeLayout>
</LinearLayout>

其他像許可權什麼的配置,用最開始給的官方地址裡面的就行了

 

順便說一下,本人是使用的安卓4.2版本開發的,手機真機調試和虛擬機調試在定位的時間間隔上面會有點誤差,也不知道什麼原因

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 舉個慄子<script> var now = new Date();// now.setDate(now.getDate()-num);// var result = '';// result+=now.getFullYear()+'-'+// (now.getMonth()+1)+'-'+// ( ...
  • Javascript 2016年12月19日整理 JS基礎 Chapter1 1. JS是一門運行在瀏覽器客戶端的腳本編程語言,前臺語言 1. 組成部分 1. ECMAscript JS標準 2. DOM 通過JS操作網頁元素 3. BOM 通過調用API操作瀏覽器 2. 特點: 封裝,繼承,多態 ...
  • 什麼是應用程式緩存(Application Cache)? HTML5 引入了應用程式緩存,這意味著 web 應用可進行緩存,並可在沒有網際網路連接時進行訪問。 應用程式緩存為應用帶來三個優勢: 離線瀏覽 - 用戶可在應用離線時使用它們 速度 - 已緩存資源載入得更快 減少伺服器負載 - 瀏覽器將只從 ...
  • CSS學習筆記 2016年12月15日整理 CSS基礎 Chapter1 在console輸入escape("宋體") ENTER 就會出現unicode編碼 顯示"%u5B8B%u4F53" 就是\5B8B\4F53 font family: 中文,英文,最好的是unicode編碼 eg. fon ...
  • HTML學習筆記 2016年12月15日整理 Chapter1 1. 1. scheme: 定義網際網路服務的類型,常見的為http 2. host: 定義域主機(http的預設主機是www) 3. domain: 定義網際網路功能變數名稱 4. port: 定義埠號,預設是埠80 5. path: 網頁在 ...
  • attribute 是原生js dom 對象上的一個屬性,這個屬性有很多子屬性,比如 isId(判斷屬性是否是Id) , name (獲取屬性名稱) , value (獲取屬性值),attributes 用來獲取dom元素 的所有屬性集合。 話不多說,上例子了: attrs 中就包含 input 所 ...
  • 文本超出部分隱藏,總結兩種方法。 1、單行隱藏 html代碼 css代碼 結果 當文字超過範圍的時候,超出部分會隱藏起來。 2、多行隱藏 css代碼 結果 當文字超過範圍的時候,超出部分會隱藏起來。可以設置第幾行開始隱藏。 ...
  • 看下效果先 下麵有完整的示例代碼 使用BitmapShader(著色器) 我們在繪製view 的時候 就是小學上美術課 用水彩筆在本子上畫畫 使用著色器繪製圓形圖片最簡單的理解方式 就是把bitmap當做一種顏色 設置給paint ,paint都已經有顏色了 你想讓它方了,圓了,扁了 還不是看你心情 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...