Using The Android Sensors PRO

The android device has sensors we can use in our code. We can get data coming from these resources using the SensorManager object. The following code sample shows how to do it.

package com.abelski.samples;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity {

	private SensorManager manager;
	private Sensor sensor;
	private SensorEventListener listener = null;

	@Override
	public void onResume() {
		super.onResume();
		manager.registerListener(listener, sensor,
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	@Override
	public void onPause() {
		super.onPause();
		manager.unregisterListener(listener, sensor);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		sensor = manager.getDefaultSensor(Sensor.TYPE_LIGHT);
		final EditText tf = (EditText) findViewById(R.id.tf);
		listener = new SensorEventListener() {
			public void onAccuracyChanged(Sensor sensor, int accuracy) {
				// ...
			}

			public void onSensorChanged(SensorEvent event) {
				if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
					Log.i("light","Light is "+event.values[0]);
					tf.setText("Light is " + event.values[0]);
				}
			}
		};

	}
}

The following video clip shows the execution of this code sample and explains it.

Share:

banner for the css playlist in hebrew life michael courses for programmers

The First Steps in CSS

Learn CSS using our our videos (in Hebrew) on the CSS (he) playlist on youtube. Do it now. Do it for free.

Good Trainers Collaborate with Others

It is always essential to keep an open mind and learn from others. This applies to everyone, including teachers and especially software development trainers. Software

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Update cookies preferences