1:在工程里新建libs文件夹,将开发包里的baidumapapi_vX_X_X.jar拷贝到libs根目录下,将libBaiduMapSDK_vX_X_X.so拷贝到libs\armeabi目录下
如图所示:
2:在AndroidManifest中添加开发密钥、所需权限等信息
15
12 3 4 5 6 7 8 9 10 11 12 13 14
3:在布局xml文件中添加地图控件
1
4:在应用程序创建时初始化 SDK引用的Context 全局变量
1 public class MainActivity extends Activity { 2 @Override 3 protected void onCreate(Bundle savedInstanceState) { 4 super.onCreate(savedInstanceState); 5 //在使用SDK各组件之前初始化context信息,传入ApplicationContext 6 //注意该方法要再setContentView方法之前实现 7 SDKInitializer.initialize(getApplicationContext()); 8 setContentView(R.layout.activity_main); 9 } 10 }
//在SDK各功能组件使用之前都需要调用SDKInitializer.initialize(getApplicationContext());,百度建议该方法放在Application的初始化方法中
5:创建地图Activity,管理地图生命周期
1 package com.example.testbaidu_v_3_1; 2 3 import android.content.BroadcastReceiver; 4 import android.content.Context; 5 import android.content.Intent; 6 import android.content.IntentFilter; 7 import android.os.Bundle; 8 import android.support.v7.app.ActionBarActivity; 9 import android.widget.Toast;10 11 import com.baidu.mapapi.SDKInitializer;12 import com.baidu.mapapi.map.MapView;13 14 public class MainActivity extends ActionBarActivity {15 16 private MapView mMapView = null;17 private SDKReceiver mReceiver;18 19 protected void onCreate(Bundle savedInstanceState) {20 super.onCreate(savedInstanceState);21 // 在使用SDK各组件之前初始化context信息,传入ApplicationContext22 // 注意该方法要再setContentView方法之前实现23 SDKInitializer.initialize(getApplicationContext());24 setContentView(R.layout.activity_main);25 // 获取地图控件引用26 mMapView = (MapView) findViewById(R.id.bmapView);27 28 //看baidu的Demo,发现它注册这个广播,用来监听SDKInitializer的初始化29 IntentFilter iFilter = new IntentFilter();30 iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);31 iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);32 mReceiver = new SDKReceiver();33 registerReceiver(mReceiver, iFilter);34 }35 36 protected void onDestroy() {37 super.onDestroy();38 // 在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理39 mMapView.onDestroy();40 unregisterReceiver(mReceiver);41 }42 43 @Override44 protected void onResume() {45 super.onResume();46 // 在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理47 mMapView.onResume();48 }49 50 @Override51 protected void onPause() {52 super.onPause();53 // 在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理54 mMapView.onPause();55 }56 57 public class SDKReceiver extends BroadcastReceiver {58 public void onReceive(Context context, Intent intent) {59 String s = intent.getAction();60 if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {61 Toast.makeText(MainActivity.this,62 "key 验证出错! 请在 AndroidManifest.xml 文件中检查 key 设置",63 Toast.LENGTH_SHORT).show();64 ;65 } else if (s66 .equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {67 Toast.makeText(MainActivity.this, "网络出错", Toast.LENGTH_SHORT)68 .show();69 }70 }71 }72 73 }
运行程序,即可在您的应用中显示如下地图