activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="@+id/tv2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="@+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
MainActivity
package com.example.sensordemo;
import android.app.Activity;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
SensorManager mySensorManager;
TextView tvX, tvY, tvZ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvX = (TextView) findViewById(R.id.tv1);
tvY = (TextView) findViewById(R.id.tv2);
tvZ = (TextView) findViewById(R.id.tv3);
mySensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
@Override
protected void onResume() {
mySensorManager.registerListener(mySensorListener,
mySensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER),//传感器类型
SensorManager.SENSOR_DELAY_UI);//传感器事件传递的频度
super.onResume();
}
@Override
protected void onPause() {//取消注册监听器
mySensorManager.unregisterListener(mySensorListener);
// TODO Auto-generated method stub
super.onPause();
}
private SensorEventListener mySensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == SensorManager.SENSOR_ACCELEROMETER) {// 判定是否为加速度传感器变化产生
float[]values=event.values;
tvX.setText("x轴方向上的加速度:" + values[0]);
tvY.setText("y轴方向上加速度:" + values[1]);
tvZ.setText("z轴方向上加速度:" + values[2]);
}
}
public void onAccuracyChanged(android.hardware.Sensor sensor, int accuracy) {};
};
}