package com.samples.hardware.magneticfield;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import java.util.List;

public class SensorActivity extends Activity {
 	
	private TextView text0;
	private TextView text1;
	private TextView text2;
	
	private SensorManager manager;
	private List<Sensor> sensors;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
       
		setContentView(R.layout.main);  

		text0 = (TextView)findViewById(R.id.text0);
		text1 = (TextView)findViewById(R.id.text1);
		text2 = (TextView)findViewById(R.id.text2);      
	}
	
	@Override
	public void onStart() {
		super.onStart();
		
		manager = 
			(SensorManager)getSystemService(Context.SENSOR_SERVICE);
		sensors = 
			manager.getSensorList(Sensor.TYPE_MAGNETIC_FIELD);
		
		if(sensors.size() != 0) {
			manager.registerListener(listener, 
					sensors.get(0), SensorManager.SENSOR_DELAY_NORMAL);
		}
		else {
		    AlertDialog.Builder builder = new AlertDialog.Builder(this);
		    
		    builder.setTitle(R.string.app_name);
		    builder.setMessage(R.string.error_msg);
		    builder.setPositiveButton(
		    		"OK", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int item) { 
		        	SensorActivity.this.finish();
		        }
		    });

		    builder.show();
		}
	}
   private SensorEventListener listener = new SensorEventListener(){
	   @Override
	   public void onAccuracyChanged(Sensor sensor, int accuracy) { }

	   @Override
	   public void onSensorChanged(SensorEvent sensorEvent) {
		   text0.setText(String.valueOf(sensorEvent.values[0]));
		   text1.setText(String.valueOf(sensorEvent.values[1]));
		   text2.setText(String.valueOf(sensorEvent.values[2]));
	   }   
   };
}