If you are wondering how to get the values of accelerometer on Android, this is the right place for you. Today, I will show you to display sensor values which you can use in implementing a compass.
Compass activity
package com.scamex.compass; import java.util.List; import android.app.Activity; import android.content.Context; 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 Compass extends Activity implements SensorEventListener { TextView tvvalues; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.compass); tvvalues = (TextView) findViewById(R.id.sensorvalues); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); attachSensor(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); detachSensor(); } private void attachSensor() { SensorManager sensorManager = getSensorManager(); Listsensors = sensorManager .getSensorList(Sensor.TYPE_ACCELEROMETER); if (sensors.size() > 0) { Sensor sensor = sensors.get(0); sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL); } else { } } private void detachSensor() { SensorManager sensorManager = getSensorManager(); sensorManager.unregisterListener(this); } private SensorManager getSensorManager() { return (SensorManager) getBaseContext().getSystemService( Context.SENSOR_SERVICE); } public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void onSensorChanged(SensorEvent event) { float valuex = event.values[0]; float valuey = event.values[1]; float valuez = event.values[2]; tvvalues.setText("x: " + valuex + "\n" + "y: " + valuey + "\n" + "z: " + valuez); } } Edit you main XML file and add a TextView with the ID of
android:id="@+id/sensorvalues" and run you application. That's it. The ouput:
No comments:
Post a Comment