//自定義導航圖標
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);
}
}