Android应用集成百度定位及导航

步骤如下:

Android app 调用导航_ide

  • 将以上所有so库分别放到arm64-v8a,armeabi,armeabi-v7a,x86,x86_64文件夹下
  • 将assets文件夹里的资源拷贝到/项目名/app/src/main/下【主要用于导航】
  • 将从百度定位,导航,地址转码jar包放到项目libs下
  • 将以上所有资源都放到项目libs下
  • 配置build.gradle
defaultConfig {
 multiDexEnabled true
 }
 sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
    dependencies {
    compile files('libs/BaiduLBS_Android.jar')
    }
  • 配置proguard-rules.pro
-keepattributes EnclosingMethod
-keep class com.baidu.**{*;}
-keep class vi.com.gdi.bgl.**{*;}
  • 配置AndroidManifest.xml
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />  
<uses-permission android:name="android.permission.BAIDU_LOCATION_SERVICE" />  
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  
<uses-permission android:name="android.permission.INTERNET" />  
<uses-permission android:name="android.permission.ACCES_MOCK_LOCATION" />  
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />  
<uses-permission android:name="android.permission.WAKE_LOCK" />  
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />  
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
<uses-permission android:name="android.permission.ACCESS_GPS" />  
<!-- SDK1.5需要android.permission.GET_TASKS权限判断本程序是否为当前运行的应用? -->  
<uses-permission android:name="android.permission.GET_TASKS" />  
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
<uses-permission android:name="android.permission.BROADCAST_STICKY" />  
<uses-permission android:name="android.permission.WRITE_SETTINGS" />  
<!-- 来电消音 -->  
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />  
<uses-permission android:name="android.permission.READ_PHONE_STATE" />  
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />  
<uses-permission android:name="android.permission.RECORD_AUDIO" />     
 <-- 摄影机 -->     
<uses-permission android:name="android.permission.CAMERA" />
增加百度LBS密钥,将下面的key值修改为在LBS开放平台申请的AK。

<meta-data android:name="com.baidu.lbsapi.API_KEY"  
            android:value="CVCyYeTeOnl1TDeONgGHWhva" />

定位用的service:

<service  
           android:name="com.baidu.location.f"  
           android:enabled="true"  
           android:process=":remote" />
            <service  android:name=".services.LoadLocatService"/>
  • 配置Application
public LocationService locationService;//百度定位
 /***
         * 初始化定位sdk,建议在Application中创建
         */
        locationService = new LocationService(getApplicationContext());
        // 在使用 SDK 各组间之前初始化 context 信息,传入 ApplicationContext
        SDKInitializer.initialize(getApplicationContext());
  • 添加定位类
import android.content.Context;

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

/**
 * 
 * @author baidu
 *
 */
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(BDLocationListener listener){
        boolean isSuccess = false;
        if(listener != null){
            client.registerLocationListener(listener);
            isSuccess = true;
        }
        return  isSuccess;
    }

    public void unregisterListener(BDLocationListener 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);
            isSuccess = true;
        }
        return isSuccess;
    }

    public LocationClientOption getOption(){
        return DIYoption;
    }
    /***
     * 
     * @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.setIsNeedAltitude(false);//可选,默认false,设置定位时是否需要海拔信息,默认不需要,除基础定位版本都可用
        }
        return mOption;
    }

    public void start(){
        synchronized (objLock) {
            if(client != null && !client.isStarted()){
                client.start();
            }
        }
    }
    public void stop(){
        synchronized (objLock) {
            if(client != null && client.isStarted()){
                client.stop();
            }
        }
    }

}
  • 添加自定义service
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.lenovo.service.ServiceApplication;
import com.lenovo.service.cache.SharedPrefManager;
import com.lenovo.service.entity.base.LoginData;
import com.lenovo.service.http.ErrorCode;
import com.lenovo.service.http.HttpClientManager;
import com.lenovo.service.http.NetInterface;
import com.lenovo.service.http.callback.adapter.JsonHttpCallBack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static android.support.v4.app.ActivityCompat.requestPermissions;
import static android.support.v4.app.ActivityCompat.shouldShowRequestPermissionRationale;

/**
 * Created by hankw on 16-8-30.
 */
public class LoadLocatService extends Service {

    private final String TAG = getClass().getSimpleName();

    private final int SDK_PERMISSION_REQUEST = 127;
    private String permissionInfo;
    private LocationService locService;
    private  static  final String  ORDERCODE = "orderid";
    private String orderid;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onStartCommand() is starting ");
        getPersimmions();
        locService = ((ServiceApplication) getApplication()).locationService;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand() is starting ");
        //此处获取工单编号
         orderid =   intent.getStringExtra(ORDERCODE);
        flags = START_STICKY;
        locService.registerListener(listener);
        if (flags == START_STICKY) {
            //LocationClientOption mOption = locService.getDefaultLocationClientOption();
            locService.setLocationOption(locService.getOption());
        } else {
            locService.setLocationOption(locService.getDefaultLocationClientOption());
        }
        locService.start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限,用户如果禁止,则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次,用户同意或者禁止,只会弹一次
             */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions((Activity) getApplicationContext(), permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale((Activity) getApplicationContext(), permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }

        } else {
            return true;
        }
    }


    /***
     * 定位结果回调,在此方法中处理定位结果
     */
    private BDLocationListener listener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {

            Log.d(TAG, "onReceiveLocation() is starting ");
            // TODO Auto-generated method stub
            //Log.d(TAG, "onError() == > location.getLocType() is (" + location.getLocType()+ ")");
            if (location != null && (location.getLocType() == 161 || location.getLocType() == 66)) {
                //Message locMsg = locHander.obtainMessage();
                // TODO: 16-8-31 此处进行坐标上传操作 ,需要从share中获取token,工程师编号,上面的orderId
                SharedPreferences preferences = SharedPrefManager.getSystemSharedPref(getBaseContext());
                String userCode = SharedPrefManager.getStringInSharePref(preferences, SharedPrefManager.LOGIN_USER_CODE, "userCode");
                String token = SharedPrefManager.getStringInSharePref(preferences, SharedPrefManager.LOGIN_TOKEN, "mToken");
                double longitude = location.getLongitude();
                double latitude = location.getLatitude();
                Log.d("LocationFilter", "onReceiveLocation() == > longitude is (" + longitude + ")");
                Log.d("LocationFilter", "onReceiveLocation() == > latitude is (" + latitude + ")");
                if (orderid != null &&!"userCode".equals(userCode) && !"mToken".equals(token)) {
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("token", token);
                    params.put("user_code", userCode);
                    params.put("order_code",orderid);
                    longitude = location.getLongitude();
                    latitude = location.getLatitude();
                    params.put("lng",""+longitude);
                    params.put("lat",""+latitude);
                    Log.d("LocationFilter", "UPLOAD_LOCATION() == > longitude is (" + longitude + ")");
                    Log.d("LocationFilter", "UPLOAD_LOCATION() == > latitude is (" + latitude + ")");
                    HttpClientManager.post(NetInterface.UPLOAD_LOCATION, params, new JsonHttpCallBack<LoginData>() {
                        @Override
                        public void onSuccess(LoginData result) {
                        Log.d(TAG,"initData() == > result.getStatus_code() is("+result.getStatus_code()+")");
                            if (Integer.parseInt(result.getStatus_code()) == ErrorCode.STATUS_SUCCESS) {

                            }
                        }

                        @Override
                        public void onError(Exception e) {
                            Log.d(TAG, "onError() == > Exception is (" + e.getMessage() + ")");
                        }
                    });
                }


            }
        }
    };


    @Override
    public void onDestroy() {
        super.onDestroy();
        locService.unregisterListener(listener); //注销掉监听
        locService.stop(); //停止定位服务

    }

    public static void  startLocService(Activity activity,String orderid){
        Intent intent = new Intent(activity,LoadLocatService.class);
            intent.putExtra(ORDERCODE,orderid);
            activity.startService(intent);
    }

    public static void stopLocService(Activity activity){
        Intent intent = new Intent(activity,LoadLocatService.class);
        activity.stopService(intent);
    }



}
  • 添加自定义地址转码和导航类
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNRoutePlanNode.CoordinateType;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.lenovo.service.ServiceApplication;
import com.lenovo.service.activity.BNDemoGuideActivity;
import com.lenovo.service.services.LocationService;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by hankw on 16-9-5.
 */
public class BaiduNavigation implements OnGetGeoCoderResultListener {

    private final String TAG = getClass().getSimpleName();
    public static List<Activity> activityList = new LinkedList<Activity>();
    //private Context mcontext;
    private double elongitude;
    private double elatitude;
    private String maddress;
    GeoCoder mSearch = null; // 搜索模块
    private static final String APP_FOLDER_NAME = "BNSDKSimpleDemo";
    private String mSDCardPath = null;
    private String authinfo = null;
    private LocationService locService;
    private Activity activity;
    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    private CoordinateType coType = CoordinateType.BD09LL;
    private boolean isLocation;

    public BaiduNavigation(Activity activity, double lon , double lat, String address) {
        //this.mcontext = context;
        this.elongitude = lon;
        this.elatitude = lat;
        this.maddress = address.trim();
        this.activity = activity;
        locService = ((ServiceApplication)activity.getApplication()).locationService;
        locService.registerListener(listener);
        //activityList.add(activity);
        locService.setLocationOption(locService.getDefaultLocationClientOption());

        // 初始化搜索模块,注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);
        if (initDirs()) {
            initNavi();
        }

        // 打开log开关
        //BNOuterLogUtil.setLogSwitcher(true);
        if (elongitude == 0.0 || elatitude ==0.0) {

            // Geo搜索
            if (maddress != null || !"".equals(maddress)) {
                //String city = maddress.substring(0,1);
                mSearch.geocode(new GeoCodeOption().city("").address(maddress));
            }

        } else {
            locService.start();

        }
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
        if (geoCodeResult == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(activity, "抱歉,未能找到结果,请修改地址后重试", Toast.LENGTH_LONG).show();
            final AlertDialog.Builder builder =  new AlertDialog.Builder(activity);
            final EditText inEdt = new EditText(activity);
                inEdt.setBackgroundResource(R.drawable.shape_4dpcorner_loginedit_bg);
            builder.setTitle("请输入准确的客户地址").setIcon(android.R.drawable.ic_dialog_info)
                    .setView(inEdt).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String input = inEdt.getText().toString().trim();
                    if (input.equals("")) {
                        Toast.makeText(activity, "搜索内容不能为空!", Toast.LENGTH_LONG).show();
                        return;
                    } else {
                        //String city = input.substring(0,1);
                        mSearch.geocode(new GeoCodeOption().city("").address(input));
                    }

                }
            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            Dialog dialog = builder.create();
            dialog.show();
            //return;
        } else {
            elatitude =  geoCodeResult.getLocation().latitude;
            elongitude = geoCodeResult.getLocation().longitude;
            Log.d(TAG, "onGetGeoCodeResult() == > latitude is (" + elatitude + ")");
            Log.d(TAG, "onGetGeoCodeResult() == > longitude is (" + elongitude + ")");
            locService.start();
        }


    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {

    }


    /***
     * 定位结果回调,在此方法中处理定位结果
     */
    private BDLocationListener listener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {

            Log.d(TAG, "onReceiveLocation() is starting ");
            // TODO Auto-generated method stub

            if (location != null && (location.getLocType() == 161 || location.getLocType() == 66) && !isLocation) {
                //Message locMsg = locHander.obtainMessage();
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                Log.d("LocationFilter", "handleMessage() == > latitude is (" + latitude + ")");
                Log.d("LocationFilter", "handleMessage() == > longitude is (" + longitude + ")");
                //routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL,longitude,latitude);
                locService.stop();
                routeplanToNavi(longitude,latitude,elongitude,elatitude,maddress);
                isLocation = true;
            } else {
                if (!isLocation){
                    // TODO: 16-9-2 对定位当前位置失败进行处理
                    Toast.makeText(activity, "当前位置定位失败,请到开阔地带重试", Toast.LENGTH_SHORT).show();
                    return;
                }

            }
        }
    };


    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    private void initNavi() {

        BNOuterTTSPlayerCallback ttsCallback = null;

        BaiduNaviManager.getInstance().init(activity, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {
            @Override
            public void onAuthResult(int status, String msg) {
                if (0 == status) {
                    authinfo = "导航key校验成功!";
                } else {
                    authinfo = "导航key校验失败, " + msg;
                }
                Log.d(TAG, authinfo);
            }

            public void initSuccess() {
                Log.d(TAG, "initSuccess() == >百度导航引擎初始化成功");
                initSetting();
                //routeplanToNavi(CoordinateType.BD09LL);
            }

            public void initStart() {
                Log.d(TAG, "initStart() == >百度导航引擎初始化开始");
            }

            public void initFailed() {
                Log.d(TAG, "initStart() == >百度导航引擎初始化失败");
            }


        },  null, ttsHandler, ttsPlayStateListener);

    }


    private void initSetting(){
        // 设置是否双屏显示
        BNaviSettingManager.setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        // 设置导航播报模式
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // 是否开启路况
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);
    }

    /**
     * 内部TTS播报状态回传handler
     */
    private Handler ttsHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type = msg.what;
            switch (type) {
                case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
                    //showToastMsg("Handler : TTS play start");
                    break;
                }
                case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
                    //showToastMsg("Handler : TTS play end");
                    break;
                }
                default :
                    break;
            }
        }
    };

    /**
     * 内部TTS播报状态回调接口
     */
    private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {

        @Override
        public void playEnd() {
            //showToastMsg("TTSPlayStateListener : TTS play end");
        }

        @Override
        public void playStart() {
            //showToastMsg("TTSPlayStateListener : TTS play start");
        }
    };


    private void routeplanToNavi(double mlongitude,double mlatitude,double elongitude,double elatitude,String eaddress) {
        BNRoutePlanNode sNode = null;
        BNRoutePlanNode eNode = null;
        Log.d(TAG, "routeplanToNavi() == > mlongitude ("+mlongitude+"), mlatitude ("+mlatitude+"), elongitude ("+elongitude+"), elatitude ("+elatitude+") eaddress ("+eaddress+")");
        //sNode = new BNRoutePlanNode(116.30784537597782, 40.057009624099436, "百度大厦", null, coType);
        sNode = new BNRoutePlanNode(mlongitude,mlatitude , "我的位置", null, coType);
        eNode = new BNRoutePlanNode(elongitude, elatitude, eaddress, null, coType);

        if (sNode != null && eNode != null) {
            List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
            list.add(sNode);
            list.add(eNode);
            BaiduNaviManager.getInstance().launchNavigator(activity, list, 1, true, new DemoRoutePlanListener(sNode));
        }
    }


    public class DemoRoutePlanListener implements BaiduNaviManager.RoutePlanListener {

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public DemoRoutePlanListener(BNRoutePlanNode node) {
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
            /*
             * 设置途径点以及resetEndNode会回调该接口
             */

            for (Activity ac : activityList) {

                if (ac.getClass().getName().endsWith("BNDemoGuideActivity")) {

                    return;
                }
            }
            Intent intent = new Intent(activity, BNDemoGuideActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
            intent.putExtras(bundle);
            activity.startActivity(intent);

        }

        @Override
        public void onRoutePlanFailed() {
            // TODO Auto-generated method stub
            //Toast.makeText(activity, "算路失败", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "onRoutePlanFailed() == >算路失败");
        }
    }
}
  • 添加百度导航activity
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.baidu.navisdk.adapter.BNRouteGuideManager;
import com.baidu.navisdk.adapter.BNRouteGuideManager.OnNavigationListener;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNaviBaseCallbackModel;
import com.baidu.navisdk.adapter.BaiduNaviCommonModule;
import com.baidu.navisdk.adapter.NaviModuleFactory;
import com.baidu.navisdk.adapter.NaviModuleImpl;
import com.lenovo.service.BaiduNavigation;


/**
 * 诱导界面
 *
 * @author sunhao04
 *
 */
public class BNDemoGuideActivity extends Activity {

    private final String TAG = BNDemoGuideActivity.class.getName();
    private BNRoutePlanNode mBNRoutePlanNode = null;
    private BaiduNaviCommonModule mBaiduNaviCommonModule = null;

    /*
     * 对于导航模块有两种方式来实现发起导航。 1:使用通用接口来实现 2:使用传统接口来实现
     *
     */
    // 是否使用通用接口
    private boolean useCommonInterface = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        BaiduNavigation.activityList.add(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        }
        View view = null;
        if (useCommonInterface) {
            //使用通用接口
            mBaiduNaviCommonModule = NaviModuleFactory.getNaviModuleManager().getNaviCommonModule(
                    NaviModuleImpl.BNaviCommonModuleConstants.ROUTE_GUIDE_MODULE, this,
                    BNaviBaseCallbackModel.BNaviBaseCallbackConstants.CALLBACK_ROUTEGUIDE_TYPE, mOnNavigationListener);
            if(mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onCreate();
                view = mBaiduNaviCommonModule.getView();
            }

        } else {
            //使用传统接口
            view = BNRouteGuideManager.getInstance().onCreate(this,mOnNavigationListener);
        }


        if (view != null) {
            setContentView(view);
        }

        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                mBNRoutePlanNode = (BNRoutePlanNode) bundle.getSerializable(BaiduNavigation.ROUTE_PLAN_NODE);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(useCommonInterface) {
            if(mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onResume();
            }
        } else {
            BNRouteGuideManager.getInstance().onResume();
        }



    }

    protected void onPause() {
        super.onPause();

        if(useCommonInterface) {
            if(mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onPause();
            }
        } else {
            BNRouteGuideManager.getInstance().onPause();
        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(useCommonInterface) {
            if(mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onDestroy();
            }
        } else {
            BNRouteGuideManager.getInstance().onDestroy();
        }
        BaiduNavigation.activityList.remove(this);

    }

    @Override
    protected void onStop() {
        super.onStop();
        if(useCommonInterface) {
            if(mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onStop();
            }
        } else {
            BNRouteGuideManager.getInstance().onStop();
        }

    }

    @Override
    public void onBackPressed() {
        if(useCommonInterface) {
            if(mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onBackPressed(false);
            }
        } else {
            BNRouteGuideManager.getInstance().onBackPressed(false);
        }
    }

    public void onConfigurationChanged(android.content.res.Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if(useCommonInterface) {
            if(mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onConfigurationChanged(newConfig);
            }
        } else {
            BNRouteGuideManager.getInstance().onConfigurationChanged(newConfig);
        }

    };


    @Override
    public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
        if(useCommonInterface) {
            if(mBaiduNaviCommonModule != null) {
                Bundle mBundle = new Bundle();
                mBundle.putInt(RouteGuideModuleConstants.KEY_TYPE_KEYCODE, keyCode);
                mBundle.putParcelable(RouteGuideModuleConstants.KEY_TYPE_EVENT, event);
                mBaiduNaviCommonModule.setModuleParams(RouteGuideModuleConstants.METHOD_TYPE_ON_KEY_DOWN, mBundle);
                try {
                    Boolean ret = (Boolean)mBundle.get(RET_COMMON_MODULE);
                    if(ret) {
                        return true;
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onStart() {
        super.onStart();
        // TODO Auto-generated method stub
        if(useCommonInterface) {
            if(mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onStart();
            }
        } else {
            BNRouteGuideManager.getInstance().onStart();
        }
    }


    private static final int MSG_SHOW = 1;
    private static final int MSG_HIDE = 2;
    private static final int MSG_RESET_NODE = 3;



    private OnNavigationListener mOnNavigationListener = new OnNavigationListener() {

        @Override
        public void onNaviGuideEnd() {
            //退出导航
            finish();
        }

        @Override
        public void notifyOtherAction(int actionType, int arg1, int arg2, Object obj) {

            if (actionType == 0) {
                //导航到达目的地 自动退出
                Log.i(TAG, "notifyOtherAction actionType = " + actionType + ",导航到达目的地!");
            }

            Log.i(TAG, "actionType:" + actionType + "arg1:" + arg1 + "arg2:" + arg2 + "obj:" + obj.toString());
        }

    };

    private final static String RET_COMMON_MODULE = "module.ret";

    private interface RouteGuideModuleConstants {
        final static int METHOD_TYPE_ON_KEY_DOWN = 0x01;
        final static String KEY_TYPE_KEYCODE = "keyCode";
        final static String KEY_TYPE_EVENT = "event";
    }
}

至此调用LoadLocatService startLocService()方法定位,调用BaiduNavigation()地址转码和导航。