Skip to content

Instantly share code, notes, and snippets.

@rillflow
Created May 13, 2010 09:08
Show Gist options
  • Save rillflow/399645 to your computer and use it in GitHub Desktop.
Save rillflow/399645 to your computer and use it in GitHub Desktop.
Android Sensor Test
public class Test extends Activity implements SensorEventListener
{
TextView mOriX, mOriY, mOriZ; // 방향 센서 3축값
TextView mMagX, mMagY, mMagZ; // 지자기 센서 3축값
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView ori, mag; // 센서명
ori = (TextView)findViewById(R.id.orientation);
mOriX = (TextView)findViewById(R.id.orientation_x_value);
mOriY = (TextView)findViewById(R.id.orientation_y_value);
mOriZ = (TextView)findViewById(R.id.orientation_z_value);
mag = (TextView)findViewById(R.id.magnetic);
mMagX = (TextView)findViewById(R.id.magnetic_x_value);
mMagY = (TextView)findViewById(R.id.magnetic_y_value);
mMagZ = (TextView)findViewById(R.id.magnetic_z_value);
// 센서 서비스
SensorManager sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensorList;
Sensor sensor;
// 방향 센서 등록
try
{
sensorList = sensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
sensor = sensorList.get(0);
ori.setText(sensor.getName());
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
}
catch(Exception ex) // 센서가 없으면
{
mOriX.setText("0.000");
mOriY.setText("0.000");
mOriZ.setText("0.000");
}
finally
{
sensorList = null;
sensor = null;
}
// 지자기 센서 등록
try
{
sensorList = sensorManager.getSensorList(Sensor.TYPE_MAGNETIC_FIELD);
sensor = sensorList.get(0);
mag.setText(sensor.getName());
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
}
catch(Exception ex)
{
mMagX.setText("0.000");
mMagY.setText("0.000");
mMagZ.setText("0.000");
}
}
public void onSensorChanged(SensorEvent event)
{
// 방향 센서값이 변경될 때
if(event.sensor.getType() == Sensor.TYPE_ORIENTATION)
{
mOriX.setText(String.format("%.3f", event.values[0]));
mOriY.setText(String.format("%.3f", event.values[1]));
mOriZ.setText(String.format("%.3f", event.values[2]));
}
// 지자기 센서값이 변경될 때
else if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
{
mMagX.setText(String.format("%.3f", event.values[0]));
mMagY.setText(String.format("%.3f", event.values[1]));
mMagZ.setText(String.format("%.3f", event.values[2]));
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
// TODO Auto-generated method stub
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment