First step in trying to create my own Augmented Reality app is reading the orientation sensor information of your handset. This can easily be done by getting the sensor manager and asking it to listen to a specific kind of sensor, the orientation sensor, and notifying a SensorEventListener.
A SensorEventListener will get an update on values at an interval that you can hint. The onSensorChanged method will receive an event that has an array of 3 values representing:
- Azimuth: rotation that can be considered as the compass, varying between 0 and 360.
- Pitch: rotation around your screen’s horizontal axis, between -180 and 180.
- Roll: rotation around you screen’s vertical axis, between -90 and 90.
Here is my code:
package be.emich.arlib;
import android.app.Activity;
import android.content.pm.ActivityInfo;
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 ARActivity extends Activity implements SensorEventListener {
protected TextView azimuthView;
protected TextView pitchView;
protected TextView rollView;
protected Float azimuth=null;
protected Float pitch=null;
protected Float roll=null;
protected SensorManager sensorManager;
protected Sensor sensor;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
bindComponents();
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
enableSensor();
}
public void bindComponents(){
azimuthView = (TextView)findViewById(R.id.orientationX);
pitchView = (TextView)findViewById(R.id.orientationY);
rollView = (TextView)findViewById(R.id.orientationZ);
}
public void enableSensor(){
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
public void disableSensor(){
sensorManager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
;
}
public void onSensorChanged(SensorEvent event) {
azimuth=event.values[0];
pitch=event.values[1];
roll=event.values[2];
updateViews();
}
protected void updateViews(){
azimuthView.setText(azimuth.toString());
pitchView.setText(pitch.toString());
rollView.setText(roll.toString());
}
@Override
protected void onDestroy() {
disableSensor();
super.onDestroy();
}
@Override
protected void onPause() {
disableSensor();
super.onPause();
}
@Override
protected void onResume() {
enableSensor();
super.onResume();
}
}
You’ll notice that I enable/disable the listener when the window is paused, resumed or terminated. This way I’ll avoid reading all that information when the application is not active and save on battery.
Photo credit: stevesheriw
It‘s quite in here! Why not leave a response?