7 package com.google.appinventor.components.runtime;
9 import android.hardware.Sensor;
10 import android.hardware.SensorEvent;
11 import android.hardware.SensorEventListener;
12 import android.hardware.SensorManager;
25 category = ComponentCategory.SENSORS,
26 description =
"<p>Non-visible component that measures the ambient geomagnetic field for all three physical axes " +
27 "(x, y, z) in Tesla https://en.wikipedia.org/wiki/Tesla_(unit).</p>",
28 iconName =
"images/magneticSensor.png",
30 version = YaVersion.MAGNETICFIELDSENSOR_COMPONENT_VERSION)
34 private double absoluteStrength;
35 private boolean enabled =
true;
36 private boolean listening;
37 private Sensor magneticSensor;
38 private final SensorManager sensorManager;
39 private float xStrength;
40 private float yStrength;
41 private float zStrength;
44 super(container.
$form());
48 sensorManager = (SensorManager) container.
$context().getSystemService(
"sensor");
49 magneticSensor = sensorManager.getDefaultSensor(2);
54 "sensor in the device and it is available.")
56 return sensorManager.getSensorList(2).size() > 0;
62 return magneticSensor.getMaximumRange();
66 "sensor is enabled and working.")
73 public void Enabled(
boolean localEnabled) {
74 if (enabled != localEnabled) {
75 enabled = localEnabled;
84 @
SimpleEvent(description =
"Triggers when magnetic field has changed, setting the new values in parameters.")
85 public
void MagneticChanged(
float xStrength,
float yStrength,
float zStrength,
double absoluteStrength) {
91 return absoluteStrength;
109 private Sensor getMagneticSensor() {
110 Sensor sensor = sensorManager.getDefaultSensor(2);
111 return sensor !=
null ? sensor : sensorManager.getDefaultSensor(2);
136 private void startListening() {
137 if (!listening && sensorManager !=
null && magneticSensor !=
null) {
138 sensorManager.registerListener(
this, magneticSensor, 3);
143 private void stopListening() {
144 if (listening && sensorManager !=
null) {
145 sensorManager.unregisterListener(
this);
154 if (enabled && sensorEvent.sensor.getType() == 2) {
155 float[] values = (
float[]) sensorEvent.values.clone();
156 xStrength = sensorEvent.values[0];
157 yStrength = sensorEvent.values[1];
158 zStrength = sensorEvent.values[2];
159 absoluteStrength = Math.sqrt((
double) (((xStrength * xStrength) + (yStrength * yStrength)) + (zStrength * zStrength)));