7 package com.google.appinventor.components.runtime;
9 import android.content.Context;
10 import android.hardware.Sensor;
11 import android.hardware.SensorEvent;
12 import android.hardware.SensorEventListener;
13 import android.hardware.SensorManager;
18 import java.util.List;
31 description =
"<p>Non-visible component that can measures the proximity of an object in cm " +
32 "relative to the view screen of a device. This sensor is typically used to determine " +
33 "whether a handset is being held up to a persons ear; " +
34 "i.e. lets you determine how far away an object is from a device. " +
35 "Many devices return the absolute distance, in cm, but some return only near and far values. " +
36 "In this case, the sensor usually reports its maximum range value in the far state " +
37 "and a lesser value in the near state.</p>",
40 iconName =
"images/proximitysensor.png")
46 private Sensor proximitySensor;
48 private final SensorManager sensorManager;
51 private boolean enabled;
52 private float distance=0f;
55 private boolean keepRunningWhenOnPause;
63 super(container.
$form());
69 sensorManager = (SensorManager) container.
$context().getSystemService(Context.SENSOR_SERVICE);
70 proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
83 List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_PROXIMITY);
84 return (sensors.size() > 0);
110 if (enabled && !keepRunningWhenOnPause) {
119 private void startListening() {
120 sensorManager.registerListener(
this, proximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
126 private void stopListening() {
127 sensorManager.unregisterListener(
this);
138 final float[] values = sensorEvent.values.clone();
139 distance = values[0];
154 return proximitySensor.getMaximumRange();
178 @
SimpleProperty (description =
"If enabled, then device will listen for changes in proximity.")
180 if (this.enabled == enabled) {
184 this.enabled = enabled;
198 return keepRunningWhenOnPause;
208 @
SimpleProperty (description =
"If set to true, it will keep sensing for proximity changes even when the app is not visible")
211 this.keepRunningWhenOnPause = enabled;
214 @
SimpleEvent(description =
"Triggered when distance (in cm) of the object to the device changes. ")
216 this.distance = distance;