MainActivity.java public class MainActivity extends AppCompatActivity implements SensorEventListener,View.OnClickListener { private SensorManager mSensorMgr; private TextView tvx; private TextView tvy; private TextView tvz; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bt= (Button) findViewById(R.id.bt_dsp); bt.setOnClickListener(this); Button bt_stop = (Button) findViewById(R.id.bt_stop); bt_stop.setOnClickListener(this); tvx = (TextView) findViewById(R.id.tvx); tvy = (TextView) findViewById(R.id.tvy); tvz = (TextView) findViewById(R.id.tvz); mSensorMgr = (SensorManager) getSystemService(Context.SENSOR_SERVICE); } protected void onPause() { super.onPause(); mSensorMgr.unregisterListener(this); } protected void onResume() { super.onResume(); } protected void onStop() { super.onStop(); mSensorMgr.unregisterListener(this); } public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { float[] values = event.values; tvx.setText("ACC_X: " + Float.toString(values[0])); tvy.setText("ACC_Y: " + Float.toString(values[1])); tvz.setText("ACC_Z: " + Float.toString(values[2])); } } public void onAccuracyChanged(Sensor sensor, int accuracy) { return; } @Override public void onClick(View v) { if (v.getId() == R.id.bt_dsp) { mSensorMgr.unregisterListener(this, mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)); mSensorMgr.registerListener(this, mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); return; } if (v.getId() == R.id.bt_stop) { mSensorMgr.unregisterListener(this); return; } }
activity_main.xml xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/tvx" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" tools:layout_editor_absoluteX="95dp" tools:layout_editor_absoluteY="72dp" /> <TextView android:id="@+id/tvy" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" tools:layout_editor_absoluteX="95dp" tools:layout_editor_absoluteY="114dp" /> <TextView android:id="@+id/tvz" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" tools:layout_editor_absoluteX="95dp" tools:layout_editor_absoluteY="163dp" /> <Button android:id="@+id/bt_dsp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="开始显示加速器" tools:layout_editor_absoluteX="94dp" tools:layout_editor_absoluteY="254dp" /> <Button android:id="@+id/bt_stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="停止显示加速器" tools:layout_editor_absoluteX="97dp" tools:layout_editor_absoluteY="342dp" /> </LinearLayout>