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:

The Visitor Design Pattern

The Visitor Design Pattern

The visitor design pattern allows us to add operations to objects that already exist without modifying their classes and without extending them.

The Beauty of Code

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

Update cookies preferences