android:應用程序內定位處理,百度定位,高德定位,系統定位處理.

文章來自:http://blog.csdn.net/intbird

應用內確保定位返回結果思考

如果定位結果爲網絡定位,已包含地址具體信息,直接保存結果,標記爲網絡定位

如果是gps定位信息,則只有經緯度,進行反地理編碼,保存具體信息結果,標記爲網絡定位

如果長時間取不到位置,則由定時器計時指定時間返回上次位置,也就是最長8s返回定位,標記爲定時器返回

如果始終沒有取到位置,那麼返回(0,0) ,並且後臺再次獲取位置,直到位置有效或者超出次數限制而停止

多次返回去重:如需要處理位置的重複返回多次,根據類型去獲取Map中上次該類型的信息,對比,主要判斷該類型的時間間隔,精度緯度偏差等等

關於定位的幾點體驗:

  • 百度定位:定位返回很快,很及時,推薦使用,單次定位,能很大程度的保證應用獲取位置,5.1的定位有了位置提醒;
  • 高德定位:和系統的很像,需要設置定位的米和時間,有時候不返回,有時候返回一大推,不清楚它機制是什麼,不推薦;
  • 系統定位:單純的戶外使用返回還是很不錯的,如果是做一個騎行記錄軌跡的,系統的不會產生重複記錄,即看你的參數設置,不動可不返回結果;

地圖上使用定位:

地圖上沒有自帶的定位方式,即地圖和定位是獨立的,可以讓任意的位置信息放入 我的位置 上,也可以用高德地圖,用百度定位,讓使用中的地圖去顯示小藍點,當然也可以是自己定位的任意樣式;

定位信息說明:

-百度定位:定位類型可以默認就很好;
在startLocation()時貌似會返回兩次定位結果,request好像是返回一次結果,百度定位的時間聯網時時網絡時間,時間格式是字符串,在網絡定位時會返回具體信息,如果是斷網情況下,返回當前手機時間,不定位不耗電,定位經緯度位數比較短;
-高德地圖:定位類型有三種,AmapNetWork即可,request(),應該和系統定位是一致的,返回時間爲當前手機時間,如果沒有訂到位置,getLastKnow爲上一次定位時間,lbs包含更多信息,定位經緯度位數比較長;
-系統定位:定位類型有三種,network,gps,passive,在室內使用返回成功幾乎不可能,在網絡定位還好,

應用內使用定位服務代碼:

BDLocationManager.java
GDLocationManager.java
MyAppLocation.java;
MyAppLocationListener.java;
注意使用的經緯度類型問題,由於涉及業務,Utils裏兩個文件不貼出來.定位本來就很簡單,就是處理封裝一下保證應用的位置準確和速度.有需要後臺監控位置變化的,這裏不做介紹.
1. BDLocationManager.java

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

/**
 * 百度定位5.1
 * @author intbird
 *
 */
public class BDLocationManager {

    private static BDLocationManager instance = null;
    private static final int timeOutLocation = 8*1000;
    private static final int timeSpanLocation= 500;//單次定位

    public LocationClient mLocationClient;
    private MyBDLocationListener mBDLocationListener;

    private MyAppLocationListener myAppListener;

    public static BDLocationManager getInstance(){
        if (instance == null){
           instance = new BDLocationManager();
        }
        return instance;
    }

    private BDLocationManager(){
        super();
        //定位初始化
        mLocationClient = new LocationClient(AppContext.getInstance().getApplicationContext());
        mBDLocationListener = new MyBDLocationListener();
        mLocationClient.registerLocationListener(mBDLocationListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);//打開gps
        option.setAddrType("all");
        option.setCoorType("bd09ll"); //設置座標類型
        option.setScanSpan(timeSpanLocation);
        option.setTimeOut(timeOutLocation);
        mLocationClient.setLocOption(option);
    }


    public void start(MyAppLocationListener listener){
        this.myAppListener = listener;
        if (mLocationClient != null){
            if(mLocationClient.isStarted()){
                mLocationClient.requestLocation();
            }else{
                mLocationClient.start();
            }
        }
    }

    public void destroy(){
        //mLocationClient.stop();
        //mLocationClient.unRegisterLocationListener(mBDLocationListener);
    }

    private class MyBDLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) { 
            if(location==null) return;
            int locType = location.getLocType();
            if(locType==BDLocation.TypeGpsLocation ||
                        locType==BDLocation.TypeNetWorkLocation||
                        locType==BDLocation.TypeOffLineLocation||
                        locType==BDLocation.TypeCacheLocation ){
            MyAppLocation.getInstance().onLocationSussess(location, myAppListener);
            destroy();
          }else{
              MyAppLocation.getInstance().onLocationedFaild(myAppListener);
              if(locType==BDLocation.TypeServerError){
                  MyToast.showToast(Frame.getInstance().getAppContext(),"定位失敗,請允許使用位置服務");
              }
          }
        }
    };

    public BDLocation getLastKnowLocation(){
        if(mLocationClient!=null){
            return  mLocationClient.getLastKnownLocation();
        }
        return null;
    }
}
  1. GDLocationManager.java
import android.location.Location;
import android.os.Bundle;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;

/**
 * 高德定位,NOTE:有時可能不返回定位結果;
 * @author intbird
 *
 */
public class GDLocationManager {
    private static GDLocationManager instance = null;
    private int locTimemills = 2 * 60 * 1000;
    private int locMeters  = 300;

    private LocationManagerProxy aMapManager;
    private MyAMapLocationListener aMapLocationListener;
    private MyAppLocationListener myAppListener;

    public static GDLocationManager getInstance(){
        if (instance == null){
           instance = new GDLocationManager();
        }
        return instance;
    }

    private GDLocationManager(){
        super();
        aMapManager = LocationManagerProxy.getInstance(AppContext.getInstance().getApplicationContext());
        aMapLocationListener = new MyAMapLocationListener();
    }

    public void start(MyAppLocationListener listener) {
        this.myAppListener = listener;
        if (aMapManager == null) {
            aMapManager.requestLocationData(LocationProviderProxy.AMapNetwork, locTimemills, locMeters, aMapLocationListener);
        }
    }

    public void destroy() {
        if (aMapManager != null) {
            aMapManager.removeUpdates(instance.aMapLocationListener);
            aMapManager.destroy();
        }
    }

    public AMapLocation getLastKnowLocation(){
        if(aMapManager!=null){
            return aMapManager.getLastKnownLocation(LocationProviderProxy.AMapNetwork);
        }
        return null;
    }


    private class MyAMapLocationListener implements AMapLocationListener{

        @Override
        public void onLocationChanged(Location location) {

        }

        @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(AMapLocation amapLocation) {
            if(amapLocation != null){
                if(amapLocation.getAMapException().getErrorCode() == 0) {
                    MyAppLocation.getInstance().onLocationSussess(amapLocation, myAppListener);
                    destroy();
                }else {
                    MyAppLocation.getInstance().onLocationedFaild(myAppListener);
                }
            }
        }
    }
}
  1. MyAppLocation.java;
    java
    HashMap<MapType, HashMap<String, String>> mapGpsContains
    = new HashMap<MapType, HashMap<String,String>>();//用於位置去重;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.os.CountDownTimer;
import android.text.TextUtils;
import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.baidu.location.BDLocation;
import com.idonoo.frame.GlobalInfo;
import com.idonoo.frame.dao.DbGPSInfo;
import com.idonoo.frame.types.MapType;


/**
 * 負責app內定位信息
 * @author intbird
 *
 */
public class MyAppLocation {

    private static MyAppLocation bdLocation;
    public static MyAppLocation getInstance() {
        if(bdLocation==null){
            bdLocation = new MyAppLocation();
        }
        return bdLocation;
    }

    private MyAppLocationListener locationListener;
    private CountDownTimer timer;
    private int timeOutCacelLocation = 8*1000;

    public MyAppLocation(){
        GlobalInfo.getInstance().setGpsInfo(LocationInfoUtil.getGpsInfo());//看哪個先調用;
        getTimerLocation();
    }

    /**
     * 僅用於保存位置使用.儘量使用true,已防止經緯度和地址不匹配;
     * @param isSilentRegeo 是否靜默使用定位且反地理編碼
     */
    public void startLocation(boolean isSilentRegeo){
        if(isSilentRegeo){
            MyDefaultAppLocationInfoListener listener= new MyDefaultAppLocationInfoListener();
            listener.setRegeLocationInfo(true);
            startLocation(listener);
        }else{
            startLocation(null);
        }
    }

    /**
     * App 默認定位方式接入方法
     * @param listener
     */
    public void startLocation(MyAppLocationListener listener){
        startLocation(MapType.eBaiDuMap,listener);
    }

    public void startLocation(MapType mapType,MyAppLocationListener listener){
        this.locationListener = listener;

        switch(mapType){
        case eBaiDuMap:
        default:
            BDLocationManager.getInstance().start(listener);
            break;
        case eGaoDeMap:
            GDLocationManager.getInstance().start(listener);
            break;
        }
        timer.start();
    }

    public void onLocationSussess(BDLocation location,MyAppLocationListener listener){
        LocationInfoUtil.setGPSInfo(location);
        long timeMills = System.currentTimeMillis();
        if(!TextUtils.isEmpty(location.getTime())){
            try{
               Calendar c = Calendar.getInstance();  
               c.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(location.getTime())); 
               timeMills =  c.getTimeInMillis();
            }catch(Exception ex){
            }
        }
        if(location.getLocType()==BDLocation.TypeNetWorkLocation)
            if(listener!=null) listener.setRegeLocationInfo(false);
        double[] point = LocationPointUtil.getAmapLocationFormBD(location.getLatitude(), location.getLongitude());
        onLocationSussess(timeMills,point[0],point[1],listener);
    }

    public void onLocationSussess(AMapLocation location,MyAppLocationListener listener){
        LocationInfoUtil.setGPSInfo(location);
        long timeMills = location.getTime();
        if(!TextUtils.isEmpty(location.getProvider())&&location.getProvider().contains("lbs"))
            if(listener!=null) listener.setRegeLocationInfo(false);
        onLocationSussess(timeMills,location.getLatitude(),location.getLongitude(),listener);
    }

    public void onLocationSussess(long timeMills,double lan,double lon,MyAppLocationListener listener){
        if(listener != null){
            //先返回位置,在返回位置信息,即[返回兩次];
            listener.onLocation(timeMills,lan, lon);
            if(listener.isRegeLocationInfo()){
                getLocationInfo(lan, lon, listener);
            }else{
                listener.onLocation(GlobalInfo.getInstance().getGpsInfo());
            }
        }
        timer.cancel();
    }

    public void onLocationedFaild(MyAppLocationListener listener){
        double[] locs = getLastKnowLocation();
        if(listener != null){
            listener.onLocation(-1,locs[0], locs[1]);
        }
        timer.cancel();
    }

    private void getLocationInfo(final double lan,final double lon,final MyAppLocationListener listener) {
        GDGeoManager.getInstance().reverseGeocode(new LatLonPoint(lan, lon), new GDGeoManagerListener() {
            @Override
            public void onGeocodeStart() {
            }

            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                if (i != 0 || regeocodeResult == null)
                    return;
                RegeocodeAddress address =  regeocodeResult.getRegeocodeAddress();
                if (address == null||TextUtils.isEmpty(address.getFormatAddress()))
                    return;

                DbGPSInfo gpsInfo = LocationInfoUtil.getGPSInfo(regeocodeResult);
                LocationInfoUtil.setGPSInfo(gpsInfo);
                if(listener!=null)
                    listener.onLocation(gpsInfo);
            }
        });
    }

    public double[] getLastKnowLocation(){
        BDLocation locBD = BDLocationManager.getInstance().getLastKnowLocation();
        if(locBD != null&&LocationPointUtil.isChinaLonLant(locBD.getLatitude(),locBD.getLongitude()))
            return LocationPointUtil.getAmapLocationFormBD(locBD.getLatitude(),locBD.getLongitude());

        AMapLocation locGD = GDLocationManager.getInstance().getLastKnowLocation();
        if(locGD != null&&LocationPointUtil.isChinaLonLant(locGD.getLatitude(),locGD.getLongitude()))
            return new double[]{locGD.getLatitude(),locGD.getLongitude()};

        DbGPSInfo gpsInfo = GlobalInfo.getInstance().getGpsInfo();
        if(gpsInfo!=null&&LocationPointUtil.isChinaLonLant(gpsInfo.getLatitude(),gpsInfo.getLongitude())){
            return new double[]{gpsInfo.getLatitude(), gpsInfo.getLongitude()};
        }

        startLocation(true);
        return  new double[]{0.0, 0.0};
    }

    private void getTimerLocation(){
        timer = new CountDownTimer(timeOutCacelLocation, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                if(locationListener!=null){
                    onLocationedFaild(locationListener);
                }
            }
        };
    }

    //默認定位類,可不理會;
    protected class MyDefaultAppLocationInfoListener extends MyAppLocationListener{
        @Override
        public void onLocation(long timeMills,double lan, double lon) {
        }
        @Override
        public void onLocation(DbGPSInfo info) {
        }
    }
}
  1. MyAppLocationListener.java;
import com.idonoo.frame.dao.DbGPSInfo;
import com.idonoo.frame.types.MapType;

public abstract class MyAppLocationListener {
    public boolean isRegeLocationInfo = false;
    private MapType mapType;
    public boolean isRegeLocationInfo() {
        return isRegeLocationInfo;
    }
    public void setRegeLocationInfo(boolean isNeedRese) {
        this.isRegeLocationInfo = isNeedRese;
    }
    public MapType getMapType() {
        return mapType;
    }
    public void setMapType(MapType mapType) {
        this.mapType = mapType;
    }

    public abstract void onLocation(long timeMills,double lan, double lon);

    public abstract void onLocation(DbGPSInfo info);

}

代碼基礎使用方法

直接使用,最長定位時間爲MyAppLocation中設定的8s,超過8s返回上次,或者返回0且在此進行定位請求;

MyAppLocation.getInstance().startLocation(true);//默認檢索位置的詳細信息,不返回給界面,默認後臺存儲具體信息入庫;

先返回經緯度,後返回改經緯度的具體信息,在BaseActivity中添加改代碼,在任何Activity可用;

public void startLocation(boolean isShowProgress,boolean isRegeInfo){
        if(isShowProgress)
            showProgress("獲取位置...");
        MyAppLocationInfoListener listener = new MyAppLocationInfoListener();
        listener.setRegeLocationInfo(isRegeInfo);
        MyAppLocation.getInstance().startLocation(listener);
    }

    public void onLocationed(double lan,double lon) {
        dismissProgress();
    }

    public void onLocationed(DbGPSInfo info) {
        dismissProgress();
    }

附加一個系統定位的,可無視.

package com.idonoo.shareCar.vendor.record;

import java.util.List;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;

import com.idonoo.frame.Frame;
import com.idonoo.frame.model.Locations;
import com.idonoo.frame.types.MapType;

/**
 * 系統定位
 * @author intbird
 *
 */
public class LocationAS {
    private LocationManager locationMangaerForGPS;
    private LocationManager locationMangaerForNetWork;
    private LocationManager locationMangaerForUncertain;
    private MySALocationListener locationListener;

    //minTime should be the primary tool to conserving battery life
    private int locTimemills = 2 * 60 * 1000;
    private int locMeters  = 300;

    public void setLocTimemills(int locTimemills) {
        this.locTimemills = locTimemills;
    }
    public void setLocMeters(int locMeters) {
        this.locMeters = locMeters;
    }

    public void start(LocationPointCallBack callBack){
        locationListener = new MySALocationListener(callBack);

        locationMangaerForUncertain = (LocationManager)Frame.getInstance().getAppContext().getSystemService(Context.LOCATION_SERVICE);  
        locationMangaerForGPS = (LocationManager)Frame.getInstance().getAppContext().getSystemService(Context.LOCATION_SERVICE);
        locationMangaerForNetWork = (LocationManager)Frame.getInstance().getAppContext().getSystemService(Context.LOCATION_SERVICE);

        try{//RuntimeException - if the calling thread has no Looper //SecurityException - if no suitable permission is present
            locationMangaerForUncertain.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, locTimemills, locMeters, locationListener);
            locationMangaerForGPS.requestLocationUpdates(LocationManager.GPS_PROVIDER, locTimemills, locMeters, locationListener);
            locationMangaerForNetWork.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, locTimemills, locMeters, locationListener);
        }catch(Exception ex){

        }
    }

    private void startProvider(String currentProvider,boolean enableStatus){
        if(TextUtils.isEmpty(currentProvider)) return ;
        if(locationListener==null||locationMangaerForUncertain==null) return ;
        List<String> privoders = locationMangaerForUncertain.getAllProviders();
        if(privoders==null) return ;

        if(enableStatus==false){
             Location location=null;
             for(String privoder : privoders){
                if(privoder.equalsIgnoreCase(currentProvider)||TextUtils.isEmpty(privoder)) continue;

                if(privoder.equalsIgnoreCase(LocationManager.GPS_PROVIDER)){
                    try{
                        location = locationMangaerForGPS.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        locationMangaerForGPS.requestLocationUpdates(LocationManager.GPS_PROVIDER, locTimemills, locMeters, locationListener);
                    }catch(Exception ex){
                    }
                }
                else if(privoder.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)){
                    try{
                        location = locationMangaerForNetWork.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        locationMangaerForNetWork.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, locTimemills, locMeters, locationListener);
                    }catch(Exception ex){
                    }
                }else {
                    try{
                        location = locationMangaerForUncertain.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
                        locationMangaerForUncertain.requestLocationUpdates(privoder,locTimemills, locMeters, locationListener);
                    }catch(Exception ex){
                    }
                }
             }
             if(location != null&&locationListener.mCallBack!=null){
                    locationListener.mCallBack.locted("AS",new Locations(location.getTime(),location.getTime(),location.getLongitude(),
                            location.getLatitude(), MapType.eAndServer.getValue(),location.getProvider()));
            }
        }
    }

    //the provider is disabled by the user, updates will stop.
    public void stop(){
        if(null!=locationListener&&null!=locationMangaerForGPS){
            locationMangaerForGPS.removeUpdates(locationListener);
            locationMangaerForNetWork.removeUpdates(locationListener);
            locationMangaerForUncertain.removeUpdates(locationListener);
        }
    }
    private class MySALocationListener implements LocationListener {
        private LocationPointCallBack mCallBack;
        public MySALocationListener(LocationPointCallBack callBack){
            this.mCallBack= callBack;
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
            startProvider(provider,true);
        }

        @Override
        public void onProviderDisabled(String provider) {
            startProvider(provider,false);
        }

        @Override
        public void onLocationChanged(Location location) {
            if(location != null){
                if(mCallBack != null && isCallBack(location.getTime())){
                    mCallBack.locted("AS",new Locations(location.getTime(),location.getTime(),location.getLongitude(),
                            location.getLatitude(), MapType.eAndServer.getValue(),location.getProvider()));
                }
            }
        }
    }
}

end;

發佈了81 篇原創文章 · 獲贊 14 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章