使用百度定位SDK獲取當前位置的資訊
阿新 • • 發佈:2018-12-21
1、AndroidManifext.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.njupt.bmap_mylocate" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" /> <application android:name="com.njupt.bmap_mylocate.Location" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/loc_sdk" android:theme="@style/AppTheme" > <activity android:name="com.njupt.bmap_mylocate.mainActivity" android:configChanges="orientation|keyboardHidden" android:label="@string/loc_sdk" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote" > <intent-filter> <action android:name="com.baidu.location.service_v2.2" > </action> </intent-filter> </service> </application> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" > </uses-permission> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" > </uses-permission> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" > </uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" > </uses-permission> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" > </uses-permission> <uses-permission android:name="android.permission.READ_PHONE_STATE" > </uses-permission> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" > </uses-permission> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" > </uses-permission> <uses-permission android:name="android.permission.READ_LOGS" > </uses-permission> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WRITE_SETTINGS" /></manifest>
2、activity_main.xml
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".GeofenceActivity" > <Button android:id="@+id/add" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="新增圍欄" /> <Button android:id="@+id/remove" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/add" android:text="刪除圍欄" /></RelativeLayout>
3、main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/btn_favorite_tabheader" android:layout_width="wrap_content" android:layout_height="fill_parent" android:background="@android:color/black" > <TextView android:id="@+id/textview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="@android:color/white"> </TextView> <Button android:id="@+id/StartBtn" android:layout_width="100dip" android:layout_height="50dip" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:text="開始" > </Button> <Button android:id="@+id/locBtn" android:layout_width="100dip" android:layout_height="wrap_content" android:layout_alignBottom="@+id/StartBtn" android:layout_alignTop="@+id/StartBtn" android:layout_toRightOf="@+id/StartBtn" android:text="定位" > </Button> <Button android:id="@+id/setBtn" android:layout_width="100dip" android:layout_height="50dip" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:text="設定" > </Button> <EditText android:id="@+id/addrEdit" android:layout_width="100dip" android:layout_height="40dip" android:layout_above="@+id/setBtn" android:layout_alignLeft="@+id/setBtn" android:layout_alignRight="@+id/setBtn" android:text="detail" > </EditText> <EditText android:id="@+id/edit" android:layout_width="100dip" android:layout_height="40dip" android:layout_above="@+id/setBtn" android:layout_alignLeft="@+id/addrEdit" android:layout_alignRight="@+id/addrEdit" android:text="3000" > </EditText> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/edit" android:layout_alignTop="@+id/edit" android:layout_toLeftOf="@+id/edit" android:text="掃描時間間隔 :" android:textColor="@android:color/white"> </TextView> <EditText android:id="@+id/coorEdit" android:layout_width="100dip" android:layout_height="40dip" android:layout_above="@+id/edit" android:layout_alignLeft="@+id/edit" android:layout_alignRight="@+id/edit" android:text="bd09ll" > </EditText> <CheckBox android:id="@+id/gpsCheck" android:layout_width="wrap_content" android:layout_height="40dip" android:layout_above="@+id/coorEdit" android:layout_alignRight="@+id/coorEdit" android:text="開啟GPS" android:textColor="@android:color/white" > </CheckBox> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/coorEdit" android:layout_alignTop="@+id/coorEdit" android:layout_toLeftOf="@+id/coorEdit" android:text="座標系型別 :" android:textColor="@android:color/white"> </TextView> <Button android:id="@+id/PoiReq" android:layout_width="100dip" android:layout_height="50dip" android:layout_alignBaseline="@+id/textView2" android:layout_alignBottom="@+id/textView2" android:layout_alignParentLeft="true" android:text="PoiRequest" /> <CheckBox android:id="@+id/priorityCheck" android:layout_width="100dip" android:layout_height="50dip" android:layout_alignTop="@+id/gpsCheck" android:layout_toLeftOf="@+id/locBtn" android:text="網路優先順序" android:textColor="@android:color/white"/> <Button android:id="@+id/offLineBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/gpsCheck" android:text="離線請求" /> <CheckBox android:id="@+id/isAddrInfocb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/offLineBtn" android:layout_marginBottom="14dp" android:layout_toRightOf="@+id/locBtn" android:text="是否要地址資訊" android:textColor="@android:color/white"/></RelativeLayout>
4、strings.xml
<?xml version="1.0" encoding="utf-8"?><resources> <string name="app_name">Geofence4.0</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="loc_sdk">定位SDK</string> <string name="geofence">地理圍欄</string></resources>
5、導定位SDK的jar包、armeabi目錄到lib目錄下
6、Location
package com.njupt.bmap_mylocate;import android.app.Application;import android.os.Process;import android.os.Vibrator;import android.util.Log;import android.widget.TextView;import android.widget.Toast;import com.baidu.location.BDLocation;import com.baidu.location.BDLocationListener;import com.baidu.location.BDNotifyListener;import com.baidu.location.GeofenceClient;import com.baidu.location.LocationClient;public class Location extends Application { public LocationClient mLocationClient = null;//LocationClient,定位SDK的核心類 private String mData; public MyLocationListenner myListener = new MyLocationListenner(); public TextView mTv; public NotifyLister mNotifyer=null; public Vibrator mVibrator01; @Override public void onCreate() { mLocationClient = new LocationClient( this ); /**—————————————————————————————————————————————————————————————————— * 這裡的AK和應用簽名包名繫結,如果使用在自己的工程中需要替換為自己申請的Key * —————————————————————————————————————————————————————————————————— */ mLocationClient.setAK("1d6228b653bfe637080e8c6a56f953a9");//設定已申請AccessKey mLocationClient.registerLocationListener( myListener );//註冊監聽函式: //位置提醒相關程式碼 mNotifyer = new NotifyLister(); mNotifyer.SetNotifyLocation(32.128925,118.931046,3000,"gps");//用於設定位置提醒的點的具體資訊,4個引數依次為:緯度,經度,半徑,座標型別.4個引數代表要位置提醒的點的座標,具體含義依次為:緯度,經度,距離範圍,座標系型別(gcj02,gps,bd09,bd09ll) mLocationClient.registerNotify(mNotifyer);//註冊位置提醒監聽事件: super.onCreate(); } /** * 顯示請求字串 * @param str */ public void logMsg(String str) { try { mData = str; if ( mTv != null ) mTv.setText(mData); } catch (Exception e) { e.printStackTrace(); } } /** * 監聽函式,有更新位置的時候,格式化成字串,輸出到螢幕中 */ public class MyLocationListenner implements BDLocationListener { /** * 封裝了定位SDK的定位結果,在BDLocationListener的onReceive方法中獲取。 * 通過該類使用者可以獲取error code,位置的座標,精度半徑等資訊 * * onReceiveLocation():獲取定位結果的介面。使用者自己實現這個介面後,監聽定位結果。 */ @Override public void onReceiveLocation(BDLocation location) { if (location == null) return ; StringBuffer sb = new StringBuffer(256); sb.append("time : "); sb.append(location.getTime()); sb.append("\nerror code : "); sb.append(location.getLocType());//獲取error code.161:網路定位結果 , 61:GPS定位結果 , 66:離線定位結果 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){ sb.append("\nspeed : "); sb.append(location.getSpeed()); sb.append("\nsatellite : "); sb.append(location.getSatelliteNumber()); } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){ /** * 格式化顯示地址資訊 * */ sb.append("\n省:");//獲取省份資訊 sb.append(location.getProvince()); sb.append("\n市:"); sb.append(location.getCity());//獲取城市資訊 sb.append("\n區/縣:"); sb.append(location.getDistrict());//獲取區縣資訊 sb.append("\naddr : "); sb.append(location.getAddrStr());//獲取反地理編碼 } sb.append("\nsdk version : "); sb.append(mLocationClient.getVersion());//獲取定位SDK的版本號 sb.append("\nisCellChangeFlag : "); sb.append(location.isCellChangeFlag()); logMsg(sb.toString()); System.out.println(sb.toString()); } /** * onReceivePoi(...):獲取POI資訊的介面。使用者自己實現這個介面後,監聽poi的相關結果。 */ public void onReceivePoi(BDLocation poiLocation) { if (poiLocation == null){ return ; } StringBuffer sb = new StringBuffer(256); sb.append("Poi time : "); sb.append(poiLocation.getTime()); sb.append("\nerror code : "); sb.append(poiLocation.getLocType()); sb.append("\nlatitude : "); sb.append(poiLocation.getLatitude()); sb.append("\nlontitude : "); sb.append(poiLocation.getLongitude()); sb.append("\nradius : "); sb.append(poiLocation.getRadius()); if (poiLocation.getLocType() == BDLocation.TypeNetWorkLocation){ sb.append("\naddr : "); sb.append(poiLocation.getAddrStr()); } if(poiLocation.hasPoi()){ sb.append("\nPoi:"); sb.append(poiLocation.getPoi()); }else{ sb.append("noPoi information"); } logMsg(sb.toString()); } } /** * BDNotifyListener:位置提醒介面類,用於設定位置提醒點 * @author Administrator * */ public class NotifyLister extends BDNotifyListener{ /** * onNotify(...): 位置提醒監聽事件具體實現 * mlocation表示當前位置, * distance是當前座標中心點與設定位置提醒的座標點之間的距離值。 */ public void onNotify(BDLocation mlocation, float distance){ mVibrator01.vibrate(1000); Toast.makeText(getApplicationContext(), "您好,您已經到達一個對你來說有意義的位置...", 1).show(); } } }
7、mainActivity
package com.njupt.bmap_mylocate;import java.util.regex.Pattern;import android.app.Activity;import android.app.Service;import android.content.Intent;import android.os.Bundle;import android.os.Process;import android.os.Vibrator;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.CheckBox;import android.widget.EditText;import android.widget.TextView;import com.baidu.location.LocationClient;import com.baidu.location.LocationClientOption;public class mainActivity extends Activity { private TextView mTv = null; private EditText mSpanEdit; private EditText mCoorEdit; private CheckBox mGpsCheck; private CheckBox mPriorityCheck; private Button mStartBtn; private Button mSetBtn; private Button mLocBtn; private Button mPoiBtn; private Button mOfflineBtn; private CheckBox mIsAddrInfoCheck; private boolean mIsStart; private static int count = 1; private Vibrator mVibrator01 =null; private LocationClient mLocClient; private Button geofenceBtn; public static String TAG = "LocTestDemo"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTv = (TextView)findViewById(R.id.textview); mSpanEdit = (EditText)findViewById(R.id.edit); mCoorEdit = (EditText)findViewById(R.id.coorEdit); mGpsCheck = (CheckBox)findViewById(R.id.gpsCheck); mPriorityCheck = (CheckBox)findViewById(R.id.priorityCheck); mStartBtn = (Button)findViewById(R.id.StartBtn); mLocBtn = (Button)findViewById(R.id.locBtn); mSetBtn = (Button)findViewById(R.id.setBtn); mPoiBtn = (Button)findViewById(R.id.PoiReq); mOfflineBtn = (Button)findViewById(R.id.offLineBtn); mIsAddrInfoCheck = (CheckBox)findViewById(R.id.isAddrInfocb); mIsStart = false; mLocClient = ((Location)getApplication()).mLocationClient; ((Location)getApplication()).mTv = mTv; mVibrator01 =(Vibrator)getApplication().getSystemService(Service.VIBRATOR_SERVICE); ((Location)getApplication()).mVibrator01 = mVibrator01; //開始/停止按鈕 mStartBtn.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { if (!mIsStart) { setLocationOption(); mLocClient.start();//啟動定位SDK mStartBtn.setText("停止"); mIsStart = true; } else { mLocClient.stop();//關閉定位SDK mIsStart = false; mStartBtn.setText("開始"); } Log.d(TAG, "... mStartBtn onClick... pid="+Process.myPid()+" count="+count++); } }); //定位按鈕 mLocBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mLocClient != null && mLocClient.isStarted()){ /** * 0: 正常發起了定位。 1: 服務沒有啟動。 2: 沒有監聽函式。 6: 請求間隔過短。 * 前後兩次請求定位時間間隔不能小於1000ms。 */ setLocationOption(); mLocClient.requestLocation();//發起定位,非同步獲取當前位置.定位結果在ReceiveListener的方法OnReceive方法的引數中返回。 } else Log.d(TAG, "locClient is null or not started"); Log.d(TAG, "... mlocBtn onClick... pid="+Process.myPid()+" count="+count++); Log.d(TAG,"version:"+mLocClient.getVersion()); } }); //設定按鈕 mSetBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setLocationOption(); } }); mPoiBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mLocClient.requestPoi(); } }); //離線基站定位按鈕 mOfflineBtn.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { /** * 0: 正常發起了定位。 * 1: 服務沒有啟動。 * 2: 沒有監聽函式。 */ int req = mLocClient.requestOfflineLocation();//發起離線定位,非同步獲取當前位置 Log.d("req","req:"+req); } }); } @Override public void onDestroy() { mLocClient.stop(); ((Location)getApplication()).mTv = null; super.onDestroy(); } //設定相關引數 private void setLocationOption(){ /** * setProdName ( String ): 設定產品線名稱。強烈建議您使用自定義的產品線名稱,方便我們以後為您提供更高效準確的定位服務。 * setPoiDistance( float ): 設定查詢範圍,預設值為500,即以當前定位位置為中心的半徑大小。 */ LocationClientOption option = new LocationClientOption(); option.setOpenGps(mGpsCheck.isChecked()); //設定是否開啟gps, option.setCoorType(mCoorEdit.getText().toString()); //設定座標型別 option.setServiceName("com.baidu.location.service_v2.9"); option.setPoiExtraInfo(mIsAddrInfoCheck.isChecked()); //設定是否需要POI的電話地址等詳細資訊。預設值為false,即不返回POI的電話和地址資訊。 if(mIsAddrInfoCheck.isChecked()) { option.setAddrType("all");//設定是否需要地址資訊.String 值為 all時,表示返回地址資訊。其他值都表示不返回地址資訊。 } if(null!=mSpanEdit.getText().toString()) { boolean b = isNumeric(mSpanEdit.getText().toString()); if(b) { option.setScanSpan(Integer.parseInt(mSpanEdit.getText().toString())); //設定定位模式,小於1秒則一次定位;大於等於1秒則定時定位 } }// option.setScanSpan(3000); if(mPriorityCheck.isChecked()) { option.setPriority(LocationClientOption.NetWorkFirst); //設定網路優先 } else { option.setPriority(LocationClientOption.GpsFirst); //不設定,預設是gps優先 } option.setPoiNumber(10);//設定POI個數,預設值為3。由於POI查詢比較耗費流量,設定最多返回的POI個數,以便節省流量。 option.disableCache(true);//true表示禁用快取定位,false表示啟用快取定位。 mLocClient.setLocOption(option);//設定引數 } protected boolean isNumeric(String str) { Pattern pattern = Pattern.compile("[0-9]*"); return pattern.matcher(str).matches(); } }
----------------------------------------------------總結起來,其實就是以下三步-------------------------
1、拷AndroidManifest.xml、layout、menu、strings.xml
2、導jar包
3、拷原始碼
4、做一些必要的修改