怎么在Android中使用方向传感器?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
具体如下:
public class SensorHandActivity extends GraphicsActivity { // 传感器管理对象 private SensorManager mSensorManager; // 传感器类 private Sensor mSensor; // 自定义绘制指针View private MyCompassView mView; private float[] mValues; // 传感监听 private final SensorEventListener mSensorListener = new SensorEventListener() { public void onSensorChanged(SensorEvent event) { mValues = event.values; if (mView != null) { mView.invalidate(); } } public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); mView = new MyCompassView(this); setContentView(mView); } @Override protected void onResume() { super.onResume(); mSensorManager.registerListener(mSensorListener, mSensor, SensorManager.SENSOR_DELAY_GAME); } @Override protected void onStop() { // 在onStop方法中取消注册监听 mSensorManager.unregisterListener(mSensorListener); super.onStop(); } private class MyCompassView extends View { // 定义画笔Paint private Paint mPaint; // 定义绘制指针的路径Path private Path mPath; public MyCompassView(Context context) { super(context); initPaintAndPath(); } private void initPaintAndPath() { // 初始化画笔 mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setColor(Color.BLACK); mPaint.setStyle(Paint.Style.FILL); // 初始化绘制路径 mPath = new Path(); mPath.moveTo(0, -50);// 移动到指点点 mPath.lineTo(-20, 60);// 用线条连接到指定点 mPath.lineTo(0, 50); mPath.lineTo(20, 60); mPath.close();// 关闭路径 } @Override protected void onDraw(Canvas canvas) { // 设置画面背景 canvas.drawColor(Color.WHITE); int w = canvas.getWidth(); int h = canvas.getHeight(); int cx = w / 2; int cy = h / 2; canvas.translate(cx, cy);// 移动画面,把指针放到中央 if (mValues != null) { canvas.rotate(-mValues[0]); } canvas.drawPath(mPath, mPaint); } }}
看完上述内容,你们掌握怎么在Android中使用方向传感器的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注编程网行业资讯频道,感谢各位的阅读!