//自定义导航图标
private BitmapDescriptor mIconLocation;
//自定义传感器implements SensorEventListener
private MyOrientationListener myOrientationListener;
//把监听的x方向的值存储到这里
private float mCurrentX;
//初始化图标
mIconLocation = BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher);
//初始化回调接口
myOrientationListener = new MyOrientationListener(getApplicationContext());
//设置回调接口
myOrientationListener.setOnOrientationListener(new OnOrientationListener() {
@Override
public void OnOrientationChanged(float x) {
// TODO Auto-generated method stub
//回调接口的值存入mCurrentX
mCurrentX=x;
}
});
在Activity的生命周期里面实现 与 方向识别的生命周期同步
start方法里面
//方向识别开始
myOrientationListener.start();
stop方法里面
//停止方向传感器
myOrientationListener.stop();
在本地数据设置里面
MyLocationData data = new MyLocationData.Builder()
//设置方向
.direction(mCurrentX)
//设置自定义图标
MyLocationConfiguration config = new MyLocationConfiguration(com.baidu.mapapi.map.MyLocationConfiguration.LocationMode.NORMAL,
true, mIconLocation);
mBaiduMap.setMyLocationConfigeration(config);
下面是传感器监听的实现代码
public class MyOrientationListener implements SensorEventListener{
//用来获取Seosor
private SensorManager mSensorManager;
private Sensor mSensor;
private Context mcontext;
private float lastX;
private OnOrientationListener mOnOrientationListener;
public MyOrientationListener(Context context) {
super();
context=this.mcontext;
}
@SuppressWarnings("deprecation")
//开启监听的方法
public void start(){
mSensorManager = (SensorManager) mcontext.getSystemService(Context.SENSOR_SERVICE);
if(mSensorManager!=null){
mSensor = mSensorManager.getDefaultSensor(SensorManager.SENSOR_ORIENTATION);
}
if(mSensor!=null){
//注册监听
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_UI);
}
}
//停止监听的方法
public void stop(){
mSensorManager.unregisterListener(this);
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
@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;
}
}
public void setOnOrientationListener(OnOrientationListener mOnOrientationListener) {
this.mOnOrientationListener = mOnOrientationListener;
}
//定义回调接口
public interface OnOrientationListener{
//传递改变的监听的x方向的值
void OnOrientationChanged(float x);
}
}
原文地址:http://blog.csdn.net/a4384142/article/details/46039261