Android编程之方向传感器用法示例

作者:袖梨 2022-06-25
/**
 * 传感器指针Demo
 *
 * @description:
 * @author ldm
 * @date 2016-4-25 下午5:29:18
 */
publicclassSensorHandActivityextendsGraphicsActivity {
  // 传感器管理对象
  privateSensorManager mSensorManager;
  // 传感器类
  privateSensor mSensor;
  // 自定义绘制指针View
  privateMyCompassView mView;
  /**
   * 方向传感器检测到的感应值 values[0]: Azimuth(方位),地磁北方向与y轴的角度,围绕z轴旋转(0到359)。0=North,
   * 90=East, 180=South, 270=West values[1]: Pitch(俯仰),围绕X轴旋转(-180 to 180),
   * 当Z轴向Y轴运动时是正值 values[2]: Roll(滚),围绕Y轴旋转(-90 to 90),当X轴向Z轴运动时是正值
   */
  privatefloat[] mValues;
  // 传感监听
  privatefinalSensorEventListener mSensorListener =newSensorEventListener() {
    publicvoidonSensorChanged(SensorEvent event) {
      mValues = event.values;
      if(mView !=null) {
        mView.invalidate();
      }
    }
    publicvoidonAccuracyChanged(Sensor sensor,intaccuracy) {
    }
  };
  @SuppressWarnings("deprecation")
  @Override
  protectedvoidonCreate(Bundle icicle) {
    super.onCreate(icicle);
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    mView =newMyCompassView(this);
    setContentView(mView);
  }
  @Override
  protectedvoidonResume() {
    super.onResume();
    /**
     * 在onResume方法中注册传感器监听 事件
     * 第一个参数:监听Sensor事件,第二个参数是Sensor目标种类的值,第三个参数是延迟时间的精度密度。延迟时间的精密度参数 参数
     * 延迟时间 SensorManager.SENSOR_DELAY_FASTEST 0ms
     * SensorManager.SENSOR_DELAY_GAME 20ms SensorManager.SENSOR_DELAY_UI
     * 60ms SensorManager.SENSOR_DELAY_NORMAL 200ms
     */
    mSensorManager.registerListener(mSensorListener, mSensor,
        SensorManager.SENSOR_DELAY_GAME);
  }
  @Override
  protectedvoidonStop() {
    // 在onStop方法中取消注册监听
    mSensorManager.unregisterListener(mSensorListener);
    super.onStop();
  }
  privateclassMyCompassViewextendsView {
    // 定义画笔Paint
    privatePaint mPaint;
    // 定义绘制指针的路径Path
    privatePath mPath;
    publicMyCompassView(Context context) {
      super(context);
      initPaintAndPath();
    }
    privatevoidinitPaintAndPath() {
      // 初始化画笔
      mPaint =newPaint();
      mPaint.setAntiAlias(true);
      mPaint.setColor(Color.BLACK);
      mPaint.setStyle(Paint.Style.FILL);
      // 初始化绘制路径
      mPath =newPath();
      mPath.moveTo(0, -50);// 移动到指点点
      mPath.lineTo(-20,60);// 用线条连接到指定点
      mPath.lineTo(0,50);
      mPath.lineTo(20,60);
      mPath.close();// 关闭路径
    }
    @Override
    protectedvoidonDraw(Canvas canvas) {
      // 设置画面背景
      canvas.drawColor(Color.WHITE);
      intw = canvas.getWidth();
      inth = canvas.getHeight();
      intcx = w /2;
      intcy = h /2;
      canvas.translate(cx, cy);// 移动画面,把指针放到中央
      if(mValues !=null) {
        canvas.rotate(-mValues[0]);
      }
      canvas.drawPath(mPath, mPaint);
    }
  }
}

相关文章

精彩推荐