百度定位---基礎定位

1. 定位的使用 (在activity中使用)

package com.qu.weibao.demo;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.qu.waibao.R;
import com.qu.weibao.service.LocationService;

import android.app.Activity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/***
 * 單點定位示例,用來展示基本的定位結果,配置在LocationService.java中
 * 默認配置也可以在LocationService中修改
 *
 */
public class LocationActivity extends Activity {
	private LocationService locationService;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.location);
	}
	/***
	 * 停止定位服務
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		locationService.unregisterListener(mListener); //註銷掉監聽
		locationService.stop(); //停止定位服務
		super.onStop();
	}

	/**
	 * 開啓定位服務
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub(可以在這裏對定位進行重新配置)
		super.onStart();
		locationService = ((LocationApplication) getApplication()).locationService; 
		//獲取locationservice實例,建議應用中只初始化1個location實例,然後使用,可以參考其他示例的activity,都是通過此種方式獲取locationservice實例的
		locationService.registerListener(mListener);
		//註冊監聽

		//根據不同的業務需求,重新配置定位信息
		int type = getIntent().getIntExtra("from", 0);
		if (type == 0) {
			locationService.setLocationOption(locationService.getDefaultLocationClientOption());
		} else if (type == 1) {
			locationService.setLocationOption(locationService.getOption());
		}
		//開啓定位
		startLocation.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (startLocation.getText().toString().equals(getString(R.string.startlocation))) {
					locationService.start();// 定位SDK
											// start之後會默認發起一次定位請求,開發者無須判斷isstart並主動調用request
					startLocation.setText(getString(R.string.stoplocation));
				} else {
					locationService.stop();
					startLocation.setText(getString(R.string.startlocation));
				}
			}
		});
		
	}
	
	/*****
	 *
	 * 定位結果回調,重寫onReceiveLocation方法,可以直接拷貝如下代碼到自己工程中修改
	 *
	 */
	private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// TODO Auto-generated method stub
			if (null != location && location.getLocType() != BDLocation.TypeServerError) {
				StringBuffer sb = new StringBuffer(256);
				sb.append("time : ");
				/**
				 * 時間也可以使用systemClock.elapsedRealtime()方法 獲取的是自從開機以來,每次回調的時間;
				 * location.getTime() 是指服務端出本次結果的時間,如果位置不發生變化,則時間不變
				 */
				sb.append(location.getTime());
				sb.append("\nlocType : ");// 定位類型
				sb.append(location.getLocType());
				sb.append("\nlocType description : ");// *****對應的定位類型說明*****
                sb.append(location.getLocTypeDescription());
				sb.append("\nlatitude : ");// 緯度
				sb.append(location.getLatitude());
				sb.append("\nlontitude : ");// 經度
				sb.append(location.getLongitude());
				sb.append("\nradius : ");// 半徑
				sb.append(location.getRadius());
				sb.append("\nCountryCode : ");// 國家碼
				sb.append(location.getCountryCode());
				sb.append("\nCountry : ");// 國家名稱
				sb.append(location.getCountry());
				sb.append("\ncitycode : ");// 城市編碼
				sb.append(location.getCityCode());
				sb.append("\ncity : ");// 城市
				sb.append(location.getCity());
				sb.append("\nDistrict : ");// 區
				sb.append(location.getDistrict());
				sb.append("\nStreet : ");// 街道
				sb.append(location.getStreet());
				sb.append("\naddr : ");// 地址信息
				sb.append(location.getAddrStr());
				sb.append("\nUserIndoorState: ");// *****返回用戶室內外判斷結果*****
				sb.append(location.getUserIndoorState());
				sb.append("\nDirection(not all devices have value): ");
				sb.append(location.getDirection());// 方向
				sb.append("\nlocationdescribe: ");
                sb.append(location.getLocationDescribe());// 位置語義化信息
				sb.append("\nPoi: ");// POI信息
				if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
					for (int i = 0; i < location.getPoiList().size(); i++) {
						Poi poi = (Poi) location.getPoiList().get(i);
						sb.append(poi.getName() + ";");
					}
				}
				if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位結果
					sb.append("\nspeed : ");
					sb.append(location.getSpeed());// 速度 單位:km/h
					sb.append("\nsatellite : ");
					sb.append(location.getSatelliteNumber());// 衛星數目
					sb.append("\nheight : ");
					sb.append(location.getAltitude());// 海拔高度 單位:米
					sb.append("\ngps status : ");
                    sb.append(location.getGpsAccuracyStatus());// *****gps質量判斷*****
					sb.append("\ndescribe : ");
					sb.append("gps定位成功");
				} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 網絡定位結果
					// 運營商信息
				    if (location.hasAltitude()) {// *****如果有海拔高度*****
				        sb.append("\nheight : ");
	                    sb.append(location.getAltitude());// 單位:米
				    }
					sb.append("\noperationers : ");// 運營商信息
					sb.append(location.getOperators());
					sb.append("\ndescribe : ");
					sb.append("網絡定位成功");
				} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 離線定位結果
					sb.append("\ndescribe : ");
					sb.append("離線定位成功,離線定位結果也是有效的");
				} else if (location.getLocType() == BDLocation.TypeServerError) {
					sb.append("\ndescribe : ");
					sb.append("服務端網絡定位失敗,可以反饋IMEI號和大體定位時間到[email protected],會有人追查原因");
				} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
					sb.append("\ndescribe : ");
					sb.append("網絡不同導致定位失敗,請檢查網絡是否通暢");
				} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
					sb.append("\ndescribe : ");
					sb.append("無法獲取有效定位依據導致定位失敗,一般是由於手機的原因,處於飛行模式下一般會造成這種結果,可以試着重啓手機");
				}
			}
		}

	};
}

2.0 LocationService定位服務(定位信息的基本配置)

package com.qu.weibao.service;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import android.content.Context;

/**
 * 定位的服務
 *
 */
public class LocationService {
	private LocationClient client = null;
	private LocationClientOption mOption,DIYoption;
	private Object  objLock = new Object();
	/***
	 *  使用同步的方式設置定位客戶端同時配置定位信息
	 * @param locationContext
	 */
	public LocationService(Context locationContext){
		synchronized (objLock) {
			if(client == null){
				client = new LocationClient(locationContext);
				client.setLocOption(getDefaultLocationClientOption());
			}
		}
	}
	
	/***
	 *  註冊定位的監聽
	 * @param listener
	 * @return
	 */
	
	public boolean registerListener(BDAbstractLocationListener listener){
		boolean isSuccess = false;
		if(listener != null){
			client.registerLocationListener(listener);
			isSuccess = true;
		}
		return  isSuccess;
	}

	/**
	 * 解除註冊監聽
	 * @param listener
	 */
	public void unregisterListener(BDAbstractLocationListener listener){
		if(listener != null){
			client.unRegisterLocationListener(listener);
		}
	}
	
	/***
	 *   提供外面使用來配置定位信息
	 * @param option
	 * @return isSuccessSetOption
	 */
	public boolean setLocationOption(LocationClientOption option){
		boolean isSuccess = false;
		if(option != null){
			if(client.isStarted())
				client.stop();
			DIYoption = option;
			client.setLocOption(option);
		}
		return isSuccess;
	}

	/***
	 *  定位的基礎配置
	 * @return DefaultLocationClientOption
	 */
	public LocationClientOption getDefaultLocationClientOption(){
		if(mOption == null){
			mOption = new LocationClientOption();
			mOption.setLocationMode(LocationMode.Hight_Accuracy);//可選,默認高精度,設置定位模式,高精度,低功耗,僅設備
			mOption.setCoorType("bd09ll");//可選,默認gcj02,設置返回的定位結果座標系,如果配合百度地圖使用,建議設置爲bd09ll;
			mOption.setScanSpan(3000);//可選,默認0,即僅定位一次,設置發起連續定位請求的間隔需要大於等於1000ms纔是有效的
		    mOption.setIsNeedAddress(true);//可選,設置是否需要地址信息,默認不需要
		    mOption.setIsNeedLocationDescribe(true);//可選,設置是否需要地址描述
		    mOption.setNeedDeviceDirect(false);//可選,設置是否需要設備方向結果
		    mOption.setLocationNotify(false);//可選,默認false,設置是否當gps有效時按照1S1次頻率輸出GPS結果
		    mOption.setIgnoreKillProcess(true);//可選,默認true,定位SDK內部是一個SERVICE,並放到了獨立進程,設置是否在stop的時候殺死這個進程,默認不殺死   
		    mOption.setIsNeedLocationDescribe(true);//可選,默認false,設置是否需要位置語義化結果,可以在BDLocation.getLocationDescribe裏得到,結果類似於“在北京天安門附近”
		    mOption.setIsNeedLocationPoiList(true);//可選,默認false,設置是否需要POI結果,可以在BDLocation.getPoiList裏得到
		    mOption.SetIgnoreCacheException(false);//可選,默認false,設置是否收集CRASH信息,默認收集
			mOption.setOpenGps(true);//可選,默認false,設置是否開啓Gps定位
		    mOption.setIsNeedAltitude(false);//可選,默認false,設置定位時是否需要海拔信息,默認不需要,除基礎定位版本都可用
		 
		}
		return mOption;
	}


	/**
	 * 獲取定位的配置信息
	 * @return DIYOption 自定義Option設置
	 */
	public LocationClientOption getOption(){
		if(DIYoption == null) {
			DIYoption = new LocationClientOption();
		}
		return DIYoption;
	}

	/**
	 * 開啓定位
	 */
	public void start(){
		synchronized (objLock) {
			if(client != null && !client.isStarted()){
				client.start();
			}
		}
	}

	/**
	 * 停止定位
	 */
	public void stop(){
		synchronized (objLock) {
			if(client != null && client.isStarted()){
				client.stop();
			}
		}
	}

	/**
	 * 判斷定位是否開啓
	 * @return
	 */
	public boolean isStart() {
		return client.isStarted();
	}

	/**
	 * 獲取
	 * @return
	 */
	public boolean requestHotSpotState(){
		return client.requestHotSpotState();
	}
	
}

3.0 在Application中進行對SDK進行初始化

public class LocationApplication extends Application {
	public LocationService locationService;
    public Vibrator mVibrator;
    @Override
    public void onCreate() {
        super.onCreate();
        /***
         * 初始化定位sdk,建議在Application中創建
         */
        locationService = new LocationService(getApplicationContext());
        mVibrator =(Vibrator)getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
        SDKInitializer.initialize(getApplicationContext());
       
    }
}

4.0 相關的配置

 <!-- 聲明service組件 -->
        <service
            android:name="com.baidu.location.f"
            android:enabled="true"
            android:process=":remote" >
        </service>

        <!-- AK鑑權 -->
        <!-- meta-data需要寫在application中 -->
        <meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="pP5KTNZvASM3jegoM9TImqGjGQy0OGPC" />  <!-- http://lbsyun.baidu.com/apiconsole/key -->

 // 相關的權限

<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>
    <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>
    <uses-permission android:name="android.permission.WAKE_LOCK" >
    </uses-permission>
    <uses-permission android:name="android.permission.WRITE_SETTINGS" >
    </uses-permission>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章