首页 > 移动平台 > 详细

Android实战简易教程-第六十二枪(电子Sensor精确罗盘)

时间:2015-09-25 09:40:14      阅读:412      评论:0      收藏:0      [点我收藏+]

这里我们利用手机自带的传感器实现一个简单的电子罗盘小实例,大家可以学习到SensorManager类、SensorEventListener 及其覆写方法的使用。

首先我们创建一个布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/white"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="@string/hello"
        android:textSize="16sp"
        android:textColor="@android:color/black" >
    </TextView>

</RelativeLayout>

接着Activity文件:

package com.yayun.activity;

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.widget.TextView;

public class SensorDemo extends Activity
{
  private TextView mShowTextView;
  private SensorManager mSensorManager;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mShowTextView = (TextView) findViewById(R.id.tv_show);
    /* 取得SensorManager */
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

  }

  @Override
  protected void onResume()
  {
    super.onResume();
    /* 取得方守性的Sensor,并注册SensorEventListener */
    mSensorManager.registerListener(mSensorEventListener, mSensorManager
        .getDefaultSensor(Sensor.TYPE_ORIENTATION),
        SensorManager.SENSOR_DELAY_NORMAL);
  }

  @Override
  protected void onPause()
  {
    /* 取消注册SensorEventListener */
    mSensorManager.unregisterListener(mSensorEventListener);
    super.onPause();
  }

  private final SensorEventListener mSensorEventListener = new SensorEventListener()
  {

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy)
    {

    }

    @Override
    public void onSensorChanged(SensorEvent event)//变换
    {
      /* 判断Sensor的种类 */
      if (event.sensor.getType() == Sensor.TYPE_ORIENTATION)
      {
        /* 取得X值资料 */
        float x_data = event.values[SensorManager.DATA_X];
        if ((x_data > 0 && x_data <= 22.5) || x_data > 337.5)
        {
          mShowTextView.setText("北方" + String.valueOf(x_data));
        } else if (x_data > 22.5 && x_data <= 67.5)
        {
          mShowTextView.setText("东北方" + String.valueOf(x_data));
        } else if (x_data > 67.5 && x_data <= 112.5)
        {
          mShowTextView.setText("东方" + String.valueOf(x_data));
        } else if (x_data > 112.5 && x_data <= 157.5)
        {
          mShowTextView.setText("东南方" + String.valueOf(x_data));
        } else if (x_data > 157.5 && x_data <= 202.5)
        {
          mShowTextView.setText("南方" + String.valueOf(x_data));
        } else if (x_data > 202.5 && x_data <= 247.5)
        {
          mShowTextView.setText("西南方" + String.valueOf(x_data));
        } else if (x_data > 247.5 && x_data <= 292.5)
        {
          mShowTextView.setText("西方" + String.valueOf(x_data));
        } else if (x_data > 292.5 && x_data <= 337.5)
        {
          mShowTextView.setText("西北方" + String.valueOf(x_data));
        }
      }
    }
  };
}

这里我们主要用的几个方法:

1.public boolean registerListener (SensorEventListener listener, Sensor sensor, int samplingPeriodUs)

Parameters
listenerA SensorEventListener object.//SensorEventListener对象
sensorThe Sensor to register to.
samplingPeriodUsThe rate sensor events are delivered at. This is only a hint to the system. Events may be received faster or slower than the specified rate. Usually events are received faster. The value must be one of SENSOR_DELAY_NORMAL, SENSOR_DELAY_UI, SENSOR_DELAY_GAME, or SENSOR_DELAY_FASTEST or, the desired delay between events in microseconds. Specifying the delay in microseconds only works from Android 2.3 (API level 9) onwards. For earlier releases, you must use one of the SENSOR_DELAY_* constants.
Returns
  • true if the sensor is supported and successfully enabled.
上面的samplingPeriodUs主要有三个值:

SENSOR_DELAY_GAME  如果利用传感器开发游戏,建议使用该值。 一般大多数实时行较高的游戏使用该级别。
SENSOR_DELAY_NORMAL  默认的获取传感器数据的速度。标准延迟,对于一般的益智类游戏或者EASY界别的游戏可以使用,但过低的采样率可能对一些赛车类游戏有跳帧的现象。
SENSOR_DELAY_UI    若使用传感器更新UI, 建议使用该值。
SENSOR_DELAY_FASTEST:最低延迟,一般不是特别灵敏的处理不推荐使用,该模式可能造成手机电力大量消耗,而且由于传递的为大量的原始数据,算法处理不好将会影响游戏逻辑和UI的性能。

2.public void unregisterListener (SensorEventListener listener) //取消注册

Always make sure to disable sensors you don‘t need, especially when your activity is paused. Failing to do so can drain the battery in just a few hours. Note that the system will not disable sensors automatically when the screen turns off.

大家可以看到,文档里要求我们不需要的传感器尽量要解除注册,特别是我们的activity处于失去焦点的状态时。如果我们不按照以上去做的话,手机电池很快会被用完。

还要注意的是当屏幕关闭的时候,传感器也不会自动的解除注册。

所以我们可以利用activity 中的 onPause() 方法和onresume()方法。在onresume方法i中对传感器注册监听器,在onPause()

方法中解除注册。

3.SensorEventListener 的 onSensorChanged(SensorEvent event) 方法

首先判断传感器的种类,种类主要有:

IntTYPE_ACCELEROMETERA constant describing an accelerometer sensor type. 加速度传感器
intTYPE_ALLA constant describing all sensor types. 所有类型 A constant describing all sensor types.
intTYPE_GRAVITYA constant describing a gravity sensor type.
intTYPE_GYROSCOPEA constant describing a gyroscope sensor type 回转仪传感器
intTYPE_LIGHTA constant describing an light sensor type.光线传感器
intTYPE_LINEAR_ACCELERATIONA constant describing a linear acceleration sensor type.
intTYPE_MAGNETIC_FIELDA constant describing a magnetic field sensor type.磁场传感器
intTYPE_ORIENTATIONThis constant is deprecated. use SensorManager.getOrientation()instead. 磁场传感器
intTYPE_PRESSUREA constant describing a pressure sensor type 压力计传感器
intTYPE_PROXIMITYA constant describing an proximity sensor type.距离传感器
intTYPE_ROTATION_VECTORA constant describing a rotation vector sensor type.
intTYPE_TEMPERATUREA constant describing a temperature sensor type 温度传感器

然后根据  float x_data = event.values[SensorManager.DATA_X]; 获取角度值,根据角度值进行判断。此外还有几个常量,大家可以根据需要自行调用。

运行实例:

技术分享

喜欢的朋友请关注我和我的公众号,谢谢!

版权声明:本文为博主原创文章,未经博主允许不得转载。

Android实战简易教程-第六十二枪(电子Sensor精确罗盘)

原文:http://blog.csdn.net/yayun0516/article/details/48727891

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!