随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
上文已介绍,水平传感器传回来的第一个参数值就是代表手机绕Z轴转过的角度,也就是手机顶部与正北的夹角。在程序中通过检查该夹角就可以实现指南针应用。其实思路很简单,先准备一张图片,该图片方向指针指向正北。然后开发一个检测方向的传感器,当程序检测到手机顶部绕Z轴转过多少角度,就让指南针图片反向转过多少度,这样就实现了指针始终指向正北方。这也是指南针的原理。代码如下:
Activity:
package com.home.compass;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
public class CompassTestActivity extends Activity implements
SensorEventListener {
// 定义显示指南针图片的组件
private ImageView image;
// 记录指南针图片转过的角度
private float currentDegree = 0f;
// 定义真机的Sensor管理器
private SensorManager mSensorManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
image = (ImageView) findViewById(R.id.main_iv);
// 获取真机的传感器管理服务
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
// 为系统的方向传感器注册监听器
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onPause() {
super.onPause();
// 取消注册
mSensorManager.unregisterListener(this);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
// 如果真机上触发event的传感器类型为水平传感器类型
if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
// 获取绕Z轴转过的角度
float degree = event.values[0];
// 创建旋转动画(反向转过degree度)
RotateAnimation ra = new RotateAnimation(currentDegree, -degree,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
// 设置动画的持续时间
ra.setDuration(200);
// 设置动画结束后的保留状态
ra.setFillAfter(true);
// 启动动画
image.startAnimation(ra);
currentDegree = -degree;
}
}
}
布局XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
<ImageView
android:id="@+id/main_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/znz" />
</LinearLayout>
这里附上一张指南针的图片: