Android Tutorial - Hardware : Sensor

Using Sensor

   
package app.test;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.Settings;

public class Test extends Activity implements SensorEventListener {
    private WakeLock mWakelock;
    private PowerManager mPwrMgr;
    private WakeLock mTurnBackOn = null;
    Handler handler = new Handler();
  private SensorManager mMgr;
    private Sensor mAccel;
    private BufferedWriter mLog;
  final private SimpleDateFormat mTimeFormat = new SimpleDateFormat("HH:mm:ss - ");
  private int mSavedTimeout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mMgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
        mAccel = mMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        try {
            String filename = Environment.getExternalStorageDirectory().getAbsolutePath() +
            "/accel.log";
            mLog = new BufferedWriter(new FileWriter(filename, true));
        }
        catch(Exception e) {
          e.printStackTrace();
          finish();
        }
        mPwrMgr = (PowerManager) this.getSystemService(POWER_SERVICE);
        mWakelock = mPwrMgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Accel");
        mWakelock.acquire();
        try {
          mSavedTimeout = Settings.System.getInt(getContentResolver(), 
              Settings.System.SCREEN_OFF_TIMEOUT);
        }
        catch(Exception e) {
          mSavedTimeout = 120000;  // 2 minutes
        }
        Settings.System.putInt(getContentResolver(), 
            Settings.System.SCREEN_OFF_TIMEOUT, -1);  // always on
    }

    public BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
                handler.post(new Runnable() {
          public void run() {
            if(mTurnBackOn != null)
              mTurnBackOn.release();
                    mTurnBackOn = mPwrMgr.newWakeLock(
                            PowerManager.SCREEN_DIM_WAKE_LOCK |
                                    PowerManager.ACQUIRE_CAUSES_WAKEUP,
                            "AccelOn");
                    mTurnBackOn.acquire();
          }});
            }
        }
    };

    @Override
    protected void onStart() {
        mMgr.registerListener(this, mAccel, SensorManager.SENSOR_DELAY_NORMAL);
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mReceiver, filter);
      super.onStart();
    }

    @Override
    protected void onStop() {
        mMgr.unregisterListener(this, mAccel);
        unregisterReceiver(mReceiver);
        try {
      mLog.flush();
    } catch (IOException e) {
    }
      super.onStop();
    }

    @Override
    protected void onDestroy() {
      try {
          mLog.flush();
          mLog.close();
      }
      catch(Exception e) {
      }
        Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, mSavedTimeout);
        mWakelock.release();
        if(mTurnBackOn != null)
            mTurnBackOn.release();
        super.onDestroy();
    }
  public void onAccuracyChanged(Sensor sensor, int accuracy) {
  }
  public void onSensorChanged(SensorEvent event) {
    writeLog("Got a sensor event: " + event.values[0] + ", " +
        event.values[1] + ", " + event.values[2]);
  }
  private void writeLog(String str) {
    try {
        Date now = new Date();
        mLog.write(mTimeFormat.format(now));
      mLog.write(str);
      mLog.write("\n");
    }
    catch(IOException ioe) {
      ioe.printStackTrace();
    }
  }
}

Accelero meter Sensor

   
package app.test;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.TextView;

public class Test extends Activity implements SensorEventListener {
    private SensorManager mgr;
    private Sensor accelerometer;
    private TextView text;
  private int mRotation;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
        accelerometer = mgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        text = (TextView) findViewById(R.id.text);
        WindowManager window = (WindowManager) this.getSystemService(WINDOW_SERVICE);
        int apiLevel = Integer.parseInt(Build.VERSION.SDK);
        if(apiLevel < 8) {
            mRotation = window.getDefaultDisplay().getOrientation();
        }
        else {
          mRotation = window.getDefaultDisplay().getRotation();
        }
    }

    @Override
    protected void onResume() {
        mgr.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
      super.onResume();
    }

    @Override
    protected void onPause() {
        mgr.unregisterListener(this, accelerometer);
      super.onPause();
    }

  public void onAccuracyChanged(Sensor sensor, int accuracy) {

  }

  public void onSensorChanged(SensorEvent event) {
    String msg = String.format("X: %8.4f\nY: %8.4f\nZ: %8.4f\nRotation: %d",
            event.values[0], event.values[1], event.values[2], mRotation);
    text.setText(msg);
    text.invalidate();
  }
} 

Compass sensor

   


package app.test;

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 Test extends Activity implements SensorEventListener {
    private SensorManager mgr;
    private Sensor compass;
    private TextView text;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);

        compass = mgr.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        
        text = (TextView) findViewById(R.id.text);
    }

    @Override
    protected void onResume() {
        mgr.registerListener(this, compass, SensorManager.SENSOR_DELAY_NORMAL);
      super.onResume();
    }

    @Override
    protected void onPause() {
        mgr.unregisterListener(this, compass);
      super.onPause();
    }

  public void onAccuracyChanged(Sensor sensor, int accuracy) {

  }

  public void onSensorChanged(SensorEvent event) {
            String msg = String.format("X: %8.4f\nY: %8.4f\nZ: %8.4f",
              event.values[0], event.values[1], event.values[2]);
        text.setText(msg);
        text.invalidate();
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"  android:layout_height="fill_parent" >
  <TextView  android:id="@+id/text" android:textSize="20sp"
    android:layout_width="fill_parent"  android:layout_height="wrap_content" />
</LinearLayout>

Gravity sensor

   

package app.test;

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 Test extends Activity implements SensorEventListener {
    private SensorManager mgr;
    private Sensor accelerometer;
    private TextView text;
  private float[] gravity = new float[3];
  private float[] motion = new float[3];
  private double ratio;
  private double mAngle;
  private int counter = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
        accelerometer = mgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        text = (TextView) findViewById(R.id.text);
    }
    @Override
    protected void onResume() {
        mgr.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
      super.onResume();
    }

    @Override
    protected void onPause() {
        mgr.unregisterListener(this, accelerometer);
      super.onPause();
    }

  public void onAccuracyChanged(Sensor sensor, int accuracy) {
  }

  public void onSensorChanged(SensorEvent event) {
    for(int i=0; i<3; i++) {
            gravity [i] = (float) (0.1 * event.values[i] + 0.9 * gravity[i]);
            motion[i] = event.values[i] - gravity[i];
    }
      ratio = gravity[1]/SensorManager.GRAVITY_EARTH;
      if(ratio > 1.0) ratio = 1.0;
      if(ratio < -1.0) ratio = -1.0;
      mAngle = Math.toDegrees(Math.acos(ratio));
      if(gravity[2] < 0) {
        mAngle = -mAngle;
      }
      if(counter++ % 10 == 0) {
            String msg = String.format(
                "Raw values\nX: %8.4f\nY: %8.4f\nZ: %8.4f\n" +
          "Gravity\nX: %8.4f\nY: %8.4f\nZ: %8.4f\n" +
          "Motion\nX: %8.4f\nY: %8.4f\nZ: %8.4f\nAngle: %8.1f",
              event.values[0], event.values[1], event.values[2],
              gravity[0], gravity[1], gravity[2],
              motion[0], motion[1], motion[2],
              mAngle);
        text.setText(msg);
        text.invalidate();
        counter=1;
      }
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"  android:layout_height="fill_parent" >
  <TextView  android:id="@+id/text" android:textSize="20sp"
    android:layout_width="fill_parent"  android:layout_height="wrap_content" />
</LinearLayout>

Sensor.TYPE_GYROSCOPE

   
package app.test;

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 Test extends Activity implements SensorEventListener {
    private SensorManager mgr;
    private Sensor gyro;
    private TextView text;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
        gyro = mgr.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        text = (TextView) findViewById(R.id.text);
    }

    @Override
    protected void onResume() {
        mgr.registerListener(this, gyro, SensorManager.SENSOR_DELAY_GAME);
      super.onResume();
    }

    @Override
    protected void onPause() {
        mgr.unregisterListener(this, gyro);
      super.onPause();
    }

  public void onAccuracyChanged(Sensor sensor, int accuracy) {

  }

  public void onSensorChanged(SensorEvent event) {
    String msg = "0: " + event.values[0] + "\n" +
        "1: " + event.values[1] + "\n" +
        "2: " + event.values[2] + "\n";
    text.setText(msg);
    text.invalidate();
  }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"  android:layout_height="fill_parent" >
  <TextView  android:id="@+id/text" android:textSize="20sp"
    android:layout_width="fill_parent"  android:layout_height="wrap_content" />
</LinearLayout>

Light Sensor

   
package app.test;

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 Test extends Activity implements SensorEventListener {
    private SensorManager mgr;
    private Sensor light;
    private TextView text;
    private StringBuilder msg = new StringBuilder(2048);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);

        light = mgr.getDefaultSensor(Sensor.TYPE_LIGHT);
        
        text = (TextView) findViewById(R.id.text);
    }

    @Override
    protected void onResume() {
        mgr.registerListener(this, light, SensorManager.SENSOR_DELAY_NORMAL);
      super.onResume();
    }

    @Override
    protected void onPause() {
        mgr.unregisterListener(this, light);
      super.onPause();
    }

  public void onAccuracyChanged(Sensor sensor, int accuracy) {
    msg.insert(0, sensor.getName() + " accuracy changed: " + accuracy +
        (accuracy==1?" (LOW)":(accuracy==2?" (MED)":" (HIGH)")) + "\n");
    text.setText(msg);
    text.invalidate();
  }

  public void onSensorChanged(SensorEvent event) {
    msg.insert(0, "Got a sensor event: " + event.values[0] + " SI lux units\n");
    text.setText(msg);
    text.invalidate();
  }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"  android:layout_height="fill_parent" >
  <TextView  android:id="@+id/text" android:textSize="20sp"
    android:layout_width="fill_parent"  android:layout_height="wrap_content" />
</LinearLayout>

PROXIMITY Sensor

   

package app.test;

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 Test extends Activity implements SensorEventListener {
    private SensorManager mgr;
    private Sensor proximity;
    private TextView text;
    private StringBuilder msg = new StringBuilder(2048);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);

        proximity = mgr.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        
        text = (TextView) findViewById(R.id.text);
    }

    @Override
    protected void onResume() {
        mgr.registerListener(this, proximity, SensorManager.SENSOR_DELAY_NORMAL);
      super.onResume();
    }

    @Override
    protected void onPause() {
        mgr.unregisterListener(this, proximity);
      super.onPause();
    }

  public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // ignore
  }

  public void onSensorChanged(SensorEvent event) {
    msg.insert(0, "Got a sensor event: " + event.values[0] + " centimeters\n");
    text.setText(msg);
    text.invalidate();
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"  android:layout_height="fill_parent" >
  <TextView  android:id="@+id/text" android:textSize="20sp"
    android:layout_width="fill_parent"  android:layout_height="wrap_content" />
</LinearLayout>

Sensor List

   

package app.test;

//This file is MainActivity.java
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class Test extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView text = (TextView)findViewById(R.id.text);

        SensorManager mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);

        List<Sensor> sensors = mgr.getSensorList(Sensor.TYPE_ALL);

        StringBuilder message = new StringBuilder(2048);
        message.append("The sensors on this device are:\n");
        
        for(Sensor sensor : sensors) {
          message.append(sensor.getName() + "\n");
          message.append("  Type: " + sensorTypes.get(sensor.getType()) + "\n");
          message.append("  Vendor: " + sensor.getVendor() + "\n");
          message.append("  Version: " + sensor.getVersion() + "\n");
          message.append("  Resolution: " + sensor.getResolution() + "\n");
          message.append("  Max Range: " + sensor.getMaximumRange() + "\n");
          message.append("  Power: " + sensor.getPower() + " mA\n");
        }
        text.setText(message);
    }
    
    private HashMap<Integer, String> sensorTypes = new HashMap<Integer, String>();

    { // Initialize the map of sensor type values and names
      sensorTypes.put(Sensor.TYPE_ACCELEROMETER, "TYPE_ACCELEROMETER"); // 1
      sensorTypes.put(Sensor.TYPE_GYROSCOPE, "TYPE_GYROSCOPE"); // 4
      sensorTypes.put(Sensor.TYPE_LIGHT, "TYPE_LIGHT"); // 5
      sensorTypes.put(Sensor.TYPE_MAGNETIC_FIELD, "TYPE_MAGNETIC_FIELD"); // 2
      sensorTypes.put(Sensor.TYPE_ORIENTATION, "TYPE_ORIENTATION"); // 3
      sensorTypes.put(Sensor.TYPE_PRESSURE, "TYPE_PRESSURE"); // 6
      sensorTypes.put(Sensor.TYPE_PROXIMITY, "TYPE_PROXIMITY"); // 8
      sensorTypes.put(Sensor.TYPE_TEMPERATURE, "TYPE_TEMPERATURE"); // 7
    sensorTypes.put(Sensor.TYPE_GRAVITY, "TYPE_GRAVITY"); // 9
        sensorTypes.put(Sensor.TYPE_LINEAR_ACCELERATION,
                              "TYPE_LINEAR_ACCELERATION"); // 10
        sensorTypes.put(Sensor.TYPE_ROTATION_VECTOR,
                              "TYPE_ROTATION_VECTOR"); // 11
    }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"  android:layout_height="fill_parent" >
  <TextView  android:id="@+id/text" android:textSize="20sp"
    android:layout_width="fill_parent"  android:layout_height="wrap_content" />
</LinearLayout>

   

Temperature Sensor

   

package app.test;

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 Test extends Activity implements SensorEventListener {
    private SensorManager mgr;
    private Sensor temp;
    private TextView text;
    private StringBuilder msg = new StringBuilder(2048);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);

        temp = mgr.getDefaultSensor(Sensor.TYPE_TEMPERATURE);
        
        text = (TextView) findViewById(R.id.text);
    }

    @Override
    protected void onResume() {
        mgr.registerListener(this, temp, SensorManager.SENSOR_DELAY_NORMAL);
      super.onResume();
    }

    @Override
    protected void onPause() {
        mgr.unregisterListener(this, temp);
      super.onPause();
    }

  public void onAccuracyChanged(Sensor sensor, int accuracy) {

  }

  public void onSensorChanged(SensorEvent event) {
    float fahrenheit = event.values[0] * 9 / 5 + 32;
    msg.insert(0, "Got a sensor event: " + event.values[0] + " Celsius (" +
        fahrenheit  + " F)\n");
    text.setText(msg);
    text.invalidate();
  }
}



//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"  android:layout_height="fill_parent" >
  <TextView  android:id="@+id/text" android:textSize="20sp"
    android:layout_width="fill_parent"  android:layout_height="wrap_content" />
</LinearLayout>