Temperature Sensor : Sensor « Hardware « Android






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>

   
    
    
  








Related examples in the same category

1.Using Sensor
2.Accelero meter Sensor
3.Compass sensor
4.Gravity sensor
5.Sensor.TYPE_GYROSCOPE
6.Light Sensor
7.PROXIMITY Sensor
8.Sensor List
9.Sensor Changed event and information
10.Sensor Event Listener
11.Speed sensor
12.Sensor Test
13.Displays the values of the acceleration sensor graphically
14.Compass Activity
15.Accelerometer API
16.Using the accelerometer to integrate the device's acceleration to a position using the Verlet method.