Android百度地图,定位图标随着方向的改变而改变
2016-04-25 17:54
811 查看
代码其实很简单,用到了方向的传感器所以要用 SensorManger,具体的实现方式:
然后在你加载地图的activity实例化:
activity重写 start()和stop()方法:
这就是所有的代码了,是不是很简单。
public class MyOrientationListener implements SensorEventListener { private SensorManager mSensorManager; private Context mContext; private Sensor mSensor; private float lastX; private OnOrientationListener mOnOrientationListener; public void setmOnOrientationListener(OnOrientationListener mOnOrientationListener) { this.mOnOrientationListener = mOnOrientationListener; } public MyOrientationListener(Context context) { this.mContext = context; } public void star() { mSensorManager = (SensorManager) mContext .getSystemService(Context.SENSOR_SERVICE); if (mSensorManager != null) { //获得方向传感器 mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); } if (mSensor != null) { mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_UI); } } public void stop() { //停止定位 mSensorManager.unregisterListener(this); } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) { float x = event.values[SensorManager.DATA_X]; if (Math.abs(x - lastX) > 1.0) { if (mOnOrientationListener != null) { mOnOrientationListener.onOrientationChanged(x); } } lastX = x; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } public interface OnOrientationListener { void onOrientationChanged(float x); } }
然后在你加载地图的activity实例化:
private MyOrientationListener myOrientationListener;
//方向传感器 myOrientationListener = new MyOrientationListener(this); myOrientationListener.setmOnOrientationListener(new MyOrientationListener.OnOrientationListener() { @Override public void onOrientationChanged(float x) { mCurrentX = x; } });
activity重写 start()和stop()方法:
@Override protected void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); //开启定位的允许 myBaiduMap.setMyLocationEnabled(true); if (!mLocationClient.isStarted()) { mLocationClient.start(); //开启方向传感器 myOrientationListener.star(); } }
@Override protected void onStop() { super.onStop(); //关闭定位 myBaiduMap.setMyLocationEnabled(false); mLocationClient.stop(); //停止方向传感器 myOrientationListener.stop(); client.disconnect(); }
这就是所有的代码了,是不是很简单。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories