package com.exercise.AndroidAccelerometer;
import java.util.List;
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 AndroidAccelerometer extends Activity {
SensorManager sensorManager; boolean accelerometerPresent; Sensor accelerometerSensor;
TextView x, y, z;
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); x = (TextView)findViewById(R.id.x); y = (TextView)findViewById(R.id.y); z = (TextView)findViewById(R.id.z);
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); List sensorList = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER); if(sensorList.size() > 0){ accelerometerPresent = true; accelerometerSensor = sensorList.get(0); } else{ accelerometerPresent = false; } }
@Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); if(accelerometerPresent){ sensorManager.registerListener(accelerometerListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL); } }
@Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); if(accelerometerPresent){ sensorManager.unregisterListener(accelerometerListener); } }
private SensorEventListener accelerometerListener = new SensorEventListener(){
@Override public void onAccuracyChanged(Sensor arg0, int arg1) { // TODO Auto-generated method stub
}
@Override public void onSensorChanged(SensorEvent arg0) { // TODO Auto-generated method stub float x_value = arg0.values[0]; float y_value = arg0.values[1]; float z_value = arg0.values[2]; x.setText(String.valueOf(x_value)); y.setText(String.valueOf(y_value)); z.setText(String.valueOf(z_value)); }};}
0 komentar:
Posting Komentar