簡單實現(xiàn)安卓里百度地圖持續(xù)定位
這幾天自己研究了關(guān)于地手機上面開發(fā)安卓地圖的問題,發(fā)現(xiàn)百度官方示例demo講解百度持續(xù)定位方面還是講解的有些不清楚,本人研究了幾次之后將其弄得更詳細以便于讓各位方便學(xué)習(xí),有不足之處請在評論區(qū)指出,官方示例的網(wǎng)址是:http://lbsyun.baidu.com/index.php?title=android-locsdk/guide/v5-0
上面的網(wǎng)址已經(jīng)將安卓簡單配置百度地圖環(huán)境講解的很詳細了,再次不做贅述了,此外,可能會有人發(fā)現(xiàn)
package com.example.andoridloca;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.BDNotifyListener;//假如用到位置提醒功能,需要import該類
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.location.Poi;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.MapView;
public class MainActivity extends Activity implements OnClickListener{
MapView mMapView = null;
public static final String TAG="mian";
StringBuffer sb = new StringBuffer(256);
public StringBuilder builder=new StringBuilder();
private Button bt1;
private TextView tv1;
private DBtools DBhelper;
boolean isOpenLocation=false;
public LocationClient mLocationClient = null;
public BDLocationListener myListener = new MyLocationListener();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
DBhelper = new DBtools(this);
tv1=(TextView) findViewById(R.id.textView1);
tv1.setMovementMethod(new ScrollingMovementMethod());
bt1=(Button) findViewById(R.id.button1);
bt1.setOnClickListener(this);
mMapView = (MapView) findViewById(R.id.bmapView);
mLocationClient = new LocationClient(getApplicationContext()); //聲明LocationClient類
mLocationClient.registerLocationListener( myListener ); //注冊監(jiān)聽函數(shù)
initLocation();
}
private void initLocation(){
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationMode.Hight_Accuracy
);//可選,默認高精度,設(shè)置定位模式,高精度,低功耗,僅設(shè)備
option.setCoorType("bd09ll");//可選,默認gcj02,設(shè)置返回的定位結(jié)果坐標系
int span=0;
option.setScanSpan(span);//可選,默認0,即僅定位一次,設(shè)置發(fā)起定位請求的間隔需要大于等于1000ms才是有效的
option.setIsNeedAddress(true);//可選,設(shè)置是否需要地址信息,默認不需要
option.setOpenGps(true);//可選,默認false,設(shè)置是否使用gps
option.setLocationNotify(true);//可選,默認false,設(shè)置是否當gps有效時按照1S1次頻率輸出GPS結(jié)果
option.setIsNeedLocationDescribe(true);//可選,默認false,設(shè)置是否需要位置語義化結(jié)果,可以在BDLocation.getLocationDescribe里得到,結(jié)果類似于“在北京天安門附近”
option.setIsNeedLocationPoiList(true);//可選,默認false,設(shè)置是否需要POI結(jié)果,可以在BDLocation.getPoiList里得到
option.setIgnoreKillProcess(false);//可選,默認true,定位SDK內(nèi)部是一個SERVICE,并放到了獨立進程,設(shè)置是否在stop的時候殺死這個進程,默認不殺死
option.SetIgnoreCacheException(false);//可選,默認false,設(shè)置是否收集CRASH信息,默認收集
option.setEnableSimulateGps(false);//可選,默認false,設(shè)置是否需要過濾gps仿真結(jié)果,默認需要
mLocationClient.setLocOption(option);
}
@Override
protected void onDestroy() {
super.onDestroy();
//在activity執(zhí)行onDestroy時執(zhí)行mMapView.onDestroy(),實現(xiàn)地圖生命周期管理
mMapView.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
//在activity執(zhí)行onResume時執(zhí)行mMapView. onResume (),實現(xiàn)地圖生命周期管理
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity執(zhí)行onPause時執(zhí)行mMapView. onPause (),實現(xiàn)地圖生命周期管理
mMapView.onPause();
}
public class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
//Receive Location
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());
if (location.getLocType() == BDLocation.TypeGpsLocation){// GPS定位結(jié)果
sb.append("\nspeed : ");
sb.append(location.getSpeed());// 單位:公里每小時
sb.append("\nsatellite : ");
sb.append(location.getSatelliteNumber());
sb.append("\nheight : ");
sb.append(location.getAltitude());// 單位:米
sb.append("\ndirection : ");
sb.append(location.getDirection());// 單位度
sb.append("\naddr : ");
sb.append(location.getAddrStr());
sb.append("\ndescribe : ");
sb.append("gps定位成功");
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation){// 網(wǎng)絡(luò)定位結(jié)果
sb.append("\naddr : ");
sb.append(location.getAddrStr());
//運營商信息
sb.append("\noperationers : ");
sb.append(location.getOperators());
sb.append("\ndescribe : ");
sb.append("網(wǎng)絡(luò)定位成功");
} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 離線定位結(jié)果
sb.append("\ndescribe : ");
sb.append("離線定位成功,離線定位結(jié)果也是有效的");
} else if (location.getLocType() == BDLocation.TypeServerError) {
sb.append("\ndescribe : ");
sb.append("服務(wù)端網(wǎng)絡(luò)定位失敗,可以反饋IMEI號和大體定位時間到loc-bugs@baidu.com,會有人追查原因");
} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
sb.append("\ndescribe : ");
sb.append("網(wǎng)絡(luò)不同導(dǎo)致定位失敗,請檢查網(wǎng)絡(luò)是否通暢");
} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
sb.append("\ndescribe : ");
sb.append("無法獲取有效定位依據(jù)導(dǎo)致定位失敗,一般是由于手機的原因,處于飛行模式下一般會造成這種結(jié)果,可以試著重啟手機");
}
sb.append("\nlocationdescribe : ");
sb.append(location.getLocationDescribe());// 位置語義化信息
List<Poi> list = location.getPoiList();// POI數(shù)據(jù)
if (list != null) {
sb.append("\npoilist size = : ");
sb.append(list.size());
for (Poi p : list) {
sb.append("\npoi= : ");
sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
}
}
Log.i("BaiduLocationApiDem", sb.toString());
DBtools dbhelper=new DBtools(getApplicationContext());
ContentValues initialValues = new ContentValues();
initialValues.put("shijian",location.getTime());
initialValues.put("didian",location.getLatitude()+"--"+location.getLongitude());
dbhelper.open();
dbhelper.insert("path",initialValues);
dbhelper.close();
tv1.setText(sb.toString());
}
}
@Override
public void onClick(View arg0) {
Thread mytime=new Thread(new ThreadShow());
if(isOpenLocation){
mLocationClient.stop();
isOpenLocation=false;
}
else{
Toast.makeText(getApplicationContext(), "開啟", Toast.LENGTH_SHORT).show();
isOpenLocation=true;
//mLocationClient.start();
mytime.start();
}
}
// handler類接收數(shù)據(jù)
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
Log.i("BaiduLocationApiDem", "加以");
mLocationClient.start();
mLocationClient.requestLocation();
}
};
};
// 線程類
class ThreadShow implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
while (isOpenLocation) {
try {
mLocationClient.stop();
Thread.sleep(2000);
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
// System.out.println("send...");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("thread error...");
}
}
}
}
}
這里面關(guān)于mLocationClient.stop();mLocationClient.start(); mLocationClient.requestLocation(); 這三個函數(shù)我有必要講解一下,因為持續(xù)定位時這三個函數(shù)的配合使用很重要,官方文檔里面解釋說mLocationClient.start()函數(shù)用于開啟定位,mLocationClient.requestLocation()函數(shù)用于主動觸發(fā)定位SDK內(nèi)部定位邏輯,個人感覺差不多,兩個都會執(zhí)行我的mLocationClient的所屬類里面的邏輯代碼,可能是我的項目就這樣吧,然后是mLocationClient.stop(),此函數(shù)用于停止定位,如果持續(xù)定位的話,是需要和mLocationClient.start()函數(shù)配合使用的,具體在上面的代碼里面有展示。
切記不要將mLocationClient.start()和mLocationClient.stop()一起使用,我在網(wǎng)上查詢時好像是說一部原因,具體舉一個例子吧:
//某段代碼如果是這樣的話按照邏輯韓式會將mLocationClient所屬類的里面邏輯代碼執(zhí)行一遍,具體見MainAvtivity里面的MyLocationListener類內(nèi)容,但是實際上是不會執(zhí)行的 mLocationClient.start(); mLocationClient.stop();
所以在我的MainActivity里面我使用線程來一遍遍的執(zhí)行start和stop函數(shù),這樣就會消除剛剛說的這種效果,最后就能夠?qū)崿F(xiàn)持續(xù)定位了。
在此給出我的布局文件配合看看
<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>
其他像權(quán)限什么的配置,用最開始給的官方地址里面的就行了
順便說一下,本人是使用的安卓4.2版本開發(fā)的,手機真機調(diào)試和虛擬機調(diào)試在定位的時間間隔上面會有點誤差,也不知道什么原因
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
Android 狀態(tài)欄的設(shè)置適配問題詳解
這篇文章主要介紹了Android 狀態(tài)欄的設(shè)置適配問題詳解的相關(guān)資料,需要的朋友可以參考下2017-06-06
android動態(tài)布局之動態(tài)加入TextView和ListView的方法
這篇文章主要介紹了android動態(tài)布局之動態(tài)加入TextView和ListView的方法,涉及Android動態(tài)布局的實現(xiàn)技巧,需要的朋友可以參考下2015-05-05
Android編程獲取網(wǎng)絡(luò)連接方式及判斷手機卡所屬運營商的方法
這篇文章主要介紹了Android編程獲取網(wǎng)絡(luò)連接方式及判斷手機卡所屬運營商的方法,涉及Android針對網(wǎng)絡(luò)的判斷及本機信息的獲取技巧,需要的朋友可以參考下2016-01-01

