Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android應用集成百度定位及導航

Android應用集成百度定位及導航

編輯:關於Android編程

步驟如下:

百度定位、地址轉碼、導航所用到的so庫

將以上所有so庫分別放到arm64-v8a,armeabi,armeabi-v7a,x86,x86_64文件夾下 將assets文件夾裡的資源拷貝到/項目名/app/src/main/下【主要用於導航】<喎?/kf/ware/vc/" target="_blank" class="keylink">vc3Ryb25nPjxiciAvPg0KPGltZyBhbHQ9"導航資源" src="/uploadfile/Collfiles/20160908/20160908091801161.png" title="\" /> 將從百度定位,導航,地址轉碼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
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
     
 <-- 攝影機 -->     

增加百度LBS密鑰,將下面的key值修改為在LBS開放平台申請的AK。



定位用的service:


            
配置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 permissions = new ArrayList();
            /***
             * 定位權限為必須權限,用戶如果禁止,則每次進入都會申請
             */
            // 定位精確位置
            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 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 params = new HashMap();
                    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() {
                        @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 activityList = new LinkedList();
    //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 list = new ArrayList();
            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()地址轉碼和導航。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved