标签:
路途再远也要一步步的走不止为了生存而是对其的热爱
本讲内容:Android重力感应
一、SensorMannager传感器管理对象
1、取得SensorMannager
手机中的所有传感器都须要通过SensorMannager来访问,调用getSystemService(SENSOR_SERVICE)方法就可以拿到当前手机的传感器管理对象。
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
List<Sensor> sensors = sm.getSensorList(Sensor.TYPE_TEMPERATURE);
3、实现取得传感器Sensor状态的监听功能
public
void onAccuracyChanged(Senso sensor,int accuracy); 在感应检测到Sensor的精密度有变化时被调用到。
public void onSensorChanged(SensorEvent event); 在感应检测到Sensor的值有变化时会被调用到。
public void onSensorChanged(SensorEvent e) { x = e.values[SensorManager.DATA_X]; y = e.values[SensorManager.DATA_Y]; z = e.values[SensorManager.DATA_Z]; }
<pre name="code" class="java">sm.regesterListener(SensorEventListener listener, Sensor sensor, int rate);第一个参数:监听Sensor事件,第二个参数是Sensor目标种类的值,第三个参数是延迟(检测)时间的精度密度。延迟时间的精密度参数如下:
参数 |
延迟时间 |
SensorManager.SENSOR_DELAY_FASTEST |
0ms |
SensorManager.SENSOR_DELAY_GAME |
20ms |
SensorManager.SENSOR_DELAY_UI |
60ms |
SensorManager.SENSOR_DELAY_NORMAL |
200ms |
下面是一个重力感应应用
下面是res/layout/activity_main.xml
布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.test1.MainActivity$PlaceholderFragment" > <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="30dp" /> </RelativeLayout>
public class MainActivity extends Activity { private TextView tv; private SensorManager sm; Sensor sensor; private float x, y, z; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); sm = (SensorManager) getSystemService(SENSOR_SERVICE); sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); SensorEventListener listener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent e) { x = e.values[SensorManager.DATA_X]; y = e.values[SensorManager.DATA_Y]; z = e.values[SensorManager.DATA_Z]; setTitle("x=" + (int) x + "," + "y=" + (int) y + "," + "z="+ (int) z); tv.setText("x=" + (int) x + ", " + "y=" + (int) y + ", " + "z=" + (int) z); } @Override public void onAccuracyChanged(Sensor arg0, int arg1) { } }; sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME); } }
本讲就到这里,Take
your time and enjoy it
标签:
原文地址:http://blog.csdn.net/liguojin1230/article/details/43307461