SensorManager.java revision 5a0cb42f3ffc10502233d94fe4fae629c3111c7b
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.hardware; 18 19import android.content.Context; 20import android.os.Binder; 21import android.os.Looper; 22import android.os.ParcelFileDescriptor; 23import android.os.Process; 24import android.os.RemoteException; 25import android.os.Handler; 26import android.os.Message; 27import android.os.ServiceManager; 28import android.util.Log; 29import android.util.SparseArray; 30import android.view.IRotationWatcher; 31import android.view.IWindowManager; 32import android.view.Surface; 33 34import java.io.FileDescriptor; 35import java.io.IOException; 36import java.util.ArrayList; 37import java.util.Collections; 38import java.util.HashMap; 39import java.util.List; 40 41/** 42 * Class that lets you access the device's sensors. Get an instance of this 43 * class by calling {@link android.content.Context#getSystemService(java.lang.String) 44 * Context.getSystemService()} with an argument of {@link android.content.Context#SENSOR_SERVICE}. 45 */ 46public class SensorManager extends IRotationWatcher.Stub 47{ 48 private static final String TAG = "SensorManager"; 49 private static final float[] mTempMatrix = new float[16]; 50 51 /* NOTE: sensor IDs must be a power of 2 */ 52 53 /** 54 * A constant describing an orientation sensor. 55 * See {@link android.hardware.SensorListener SensorListener} for more details. 56 * @deprecated use {@link android.hardware.Sensor Sensor} instead. 57 */ 58 @Deprecated 59 public static final int SENSOR_ORIENTATION = 1 << 0; 60 61 /** 62 * A constant describing an accelerometer. 63 * See {@link android.hardware.SensorListener SensorListener} for more details. 64 * @deprecated use {@link android.hardware.Sensor Sensor} instead. 65 */ 66 @Deprecated 67 public static final int SENSOR_ACCELEROMETER = 1 << 1; 68 69 /** 70 * A constant describing a temperature sensor 71 * See {@link android.hardware.SensorListener SensorListener} for more details. 72 * @deprecated use {@link android.hardware.Sensor Sensor} instead. 73 */ 74 @Deprecated 75 public static final int SENSOR_TEMPERATURE = 1 << 2; 76 77 /** 78 * A constant describing a magnetic sensor 79 * See {@link android.hardware.SensorListener SensorListener} for more details. 80 * @deprecated use {@link android.hardware.Sensor Sensor} instead. 81 */ 82 @Deprecated 83 public static final int SENSOR_MAGNETIC_FIELD = 1 << 3; 84 85 /** 86 * A constant describing an ambient light sensor 87 * See {@link android.hardware.SensorListener SensorListener} for more details. 88 * @deprecated use {@link android.hardware.Sensor Sensor} instead. 89 */ 90 @Deprecated 91 public static final int SENSOR_LIGHT = 1 << 4; 92 93 /** 94 * A constant describing a proximity sensor 95 * See {@link android.hardware.SensorListener SensorListener} for more details. 96 * @deprecated use {@link android.hardware.Sensor Sensor} instead. 97 */ 98 @Deprecated 99 public static final int SENSOR_PROXIMITY = 1 << 5; 100 101 /** 102 * A constant describing a Tricorder 103 * See {@link android.hardware.SensorListener SensorListener} for more details. 104 * @deprecated use {@link android.hardware.Sensor Sensor} instead. 105 */ 106 @Deprecated 107 public static final int SENSOR_TRICORDER = 1 << 6; 108 109 /** 110 * A constant describing an orientation sensor. 111 * See {@link android.hardware.SensorListener SensorListener} for more details. 112 * @deprecated use {@link android.hardware.Sensor Sensor} instead. 113 */ 114 @Deprecated 115 public static final int SENSOR_ORIENTATION_RAW = 1 << 7; 116 117 /** A constant that includes all sensors */ 118 @Deprecated 119 public static final int SENSOR_ALL = 0x7F; 120 121 /** Smallest sensor ID */ 122 @Deprecated 123 public static final int SENSOR_MIN = SENSOR_ORIENTATION; 124 125 /** Largest sensor ID */ 126 @Deprecated 127 public static final int SENSOR_MAX = ((SENSOR_ALL + 1)>>1); 128 129 130 /** Index of the X value in the array returned by 131 * {@link android.hardware.SensorListener#onSensorChanged} */ 132 @Deprecated 133 public static final int DATA_X = 0; 134 /** Index of the Y value in the array returned by 135 * {@link android.hardware.SensorListener#onSensorChanged} */ 136 @Deprecated 137 public static final int DATA_Y = 1; 138 /** Index of the Z value in the array returned by 139 * {@link android.hardware.SensorListener#onSensorChanged} */ 140 @Deprecated 141 public static final int DATA_Z = 2; 142 143 /** Offset to the untransformed values in the array returned by 144 * {@link android.hardware.SensorListener#onSensorChanged} */ 145 @Deprecated 146 public static final int RAW_DATA_INDEX = 3; 147 148 /** Index of the untransformed X value in the array returned by 149 * {@link android.hardware.SensorListener#onSensorChanged} */ 150 @Deprecated 151 public static final int RAW_DATA_X = 3; 152 /** Index of the untransformed Y value in the array returned by 153 * {@link android.hardware.SensorListener#onSensorChanged} */ 154 @Deprecated 155 public static final int RAW_DATA_Y = 4; 156 /** Index of the untransformed Z value in the array returned by 157 * {@link android.hardware.SensorListener#onSensorChanged} */ 158 @Deprecated 159 public static final int RAW_DATA_Z = 5; 160 161 162 /** Standard gravity (g) on Earth. This value is equivalent to 1G */ 163 public static final float STANDARD_GRAVITY = 9.80665f; 164 165 /** values returned by the accelerometer in various locations in the universe. 166 * all values are in SI units (m/s^2) */ 167 public static final float GRAVITY_SUN = 275.0f; 168 public static final float GRAVITY_MERCURY = 3.70f; 169 public static final float GRAVITY_VENUS = 8.87f; 170 public static final float GRAVITY_EARTH = 9.80665f; 171 public static final float GRAVITY_MOON = 1.6f; 172 public static final float GRAVITY_MARS = 3.71f; 173 public static final float GRAVITY_JUPITER = 23.12f; 174 public static final float GRAVITY_SATURN = 8.96f; 175 public static final float GRAVITY_URANUS = 8.69f; 176 public static final float GRAVITY_NEPTUNE = 11.0f; 177 public static final float GRAVITY_PLUTO = 0.6f; 178 public static final float GRAVITY_DEATH_STAR_I = 0.000000353036145f; 179 public static final float GRAVITY_THE_ISLAND = 4.815162342f; 180 181 182 /** Maximum magnetic field on Earth's surface */ 183 public static final float MAGNETIC_FIELD_EARTH_MAX = 60.0f; 184 185 /** Minimum magnetic field on Earth's surface */ 186 public static final float MAGNETIC_FIELD_EARTH_MIN = 30.0f; 187 188 189 /** Various luminance values during the day (lux) */ 190 public static final float LIGHT_SUNLIGHT_MAX = 120000.0f; 191 public static final float LIGHT_SUNLIGHT = 110000.0f; 192 public static final float LIGHT_SHADE = 20000.0f; 193 public static final float LIGHT_OVERCAST = 10000.0f; 194 public static final float LIGHT_SUNRISE = 400.0f; 195 public static final float LIGHT_CLOUDY = 100.0f; 196 /** Various luminance values during the night (lux) */ 197 public static final float LIGHT_FULLMOON = 0.25f; 198 public static final float LIGHT_NO_MOON = 0.001f; 199 200 /** get sensor data as fast as possible */ 201 public static final int SENSOR_DELAY_FASTEST = 0; 202 /** rate suitable for games */ 203 public static final int SENSOR_DELAY_GAME = 1; 204 /** rate suitable for the user interface */ 205 public static final int SENSOR_DELAY_UI = 2; 206 /** rate (default) suitable for screen orientation changes */ 207 public static final int SENSOR_DELAY_NORMAL = 3; 208 209 210 /** The values returned by this sensor cannot be trusted, calibration 211 * is needed or the environment doesn't allow readings */ 212 public static final int SENSOR_STATUS_UNRELIABLE = 0; 213 214 /** This sensor is reporting data with low accuracy, calibration with the 215 * environment is needed */ 216 public static final int SENSOR_STATUS_ACCURACY_LOW = 1; 217 218 /** This sensor is reporting data with an average level of accuracy, 219 * calibration with the environment may improve the readings */ 220 public static final int SENSOR_STATUS_ACCURACY_MEDIUM = 2; 221 222 /** This sensor is reporting data with maximum accuracy */ 223 public static final int SENSOR_STATUS_ACCURACY_HIGH = 3; 224 225 /** see {@link #remapCoordinateSystem} */ 226 public static final int AXIS_X = 1; 227 /** see {@link #remapCoordinateSystem} */ 228 public static final int AXIS_Y = 2; 229 /** see {@link #remapCoordinateSystem} */ 230 public static final int AXIS_Z = 3; 231 /** see {@link #remapCoordinateSystem} */ 232 public static final int AXIS_MINUS_X = AXIS_X | 0x80; 233 /** see {@link #remapCoordinateSystem} */ 234 public static final int AXIS_MINUS_Y = AXIS_Y | 0x80; 235 /** see {@link #remapCoordinateSystem} */ 236 public static final int AXIS_MINUS_Z = AXIS_Z | 0x80; 237 238 /*-----------------------------------------------------------------------*/ 239 240 private ISensorService mSensorService; 241 Looper mMainLooper; 242 @SuppressWarnings("deprecation") 243 private HashMap<SensorListener, LegacyListener> mLegacyListenersMap = 244 new HashMap<SensorListener, LegacyListener>(); 245 246 /*-----------------------------------------------------------------------*/ 247 248 private static final int SENSOR_DISABLE = -1; 249 private static boolean sSensorModuleInitialized = false; 250 private static ArrayList<Sensor> sFullSensorsList = new ArrayList<Sensor>(); 251 private static SparseArray<List<Sensor>> sSensorListByType = new SparseArray<List<Sensor>>(); 252 private static IWindowManager sWindowManager; 253 private static int sRotation = Surface.ROTATION_0; 254 /* The thread and the sensor list are global to the process 255 * but the actual thread is spawned on demand */ 256 private static SensorThread sSensorThread; 257 258 // Used within this module from outside SensorManager, don't make private 259 static SparseArray<Sensor> sHandleToSensor = new SparseArray<Sensor>(); 260 static final ArrayList<ListenerDelegate> sListeners = 261 new ArrayList<ListenerDelegate>(); 262 263 /*-----------------------------------------------------------------------*/ 264 265 static private class SensorThread { 266 267 Thread mThread; 268 269 SensorThread() { 270 // this gets to the sensor module. We can have only one per process. 271 sensors_data_init(); 272 } 273 274 @Override 275 protected void finalize() { 276 sensors_data_uninit(); 277 } 278 279 // must be called with sListeners lock 280 void startLocked(ISensorService service) { 281 try { 282 if (mThread == null) { 283 ParcelFileDescriptor fd = service.getDataChanel(); 284 mThread = new Thread(new SensorThreadRunnable(fd), 285 SensorThread.class.getName()); 286 mThread.start(); 287 } 288 } catch (RemoteException e) { 289 Log.e(TAG, "RemoteException in startLocked: ", e); 290 } 291 } 292 293 private class SensorThreadRunnable implements Runnable { 294 private ParcelFileDescriptor mSensorDataFd; 295 SensorThreadRunnable(ParcelFileDescriptor fd) { 296 mSensorDataFd = fd; 297 } 298 public void run() { 299 //Log.d(TAG, "entering main sensor thread"); 300 final float[] values = new float[3]; 301 final int[] status = new int[1]; 302 final long timestamp[] = new long[1]; 303 Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY); 304 305 if (mSensorDataFd == null) { 306 Log.e(TAG, "mSensorDataFd == NULL, exiting"); 307 synchronized (sListeners) { 308 mThread = null; 309 } 310 return; 311 } 312 // this thread is guaranteed to be unique 313 sensors_data_open(mSensorDataFd.getFileDescriptor()); 314 try { 315 mSensorDataFd.close(); 316 } catch (IOException e) { 317 // *shrug* 318 Log.e(TAG, "IOException: ", e); 319 } 320 mSensorDataFd = null; 321 322 323 while (true) { 324 // wait for an event 325 final int sensor = sensors_data_poll(values, status, timestamp); 326 327 int accuracy = status[0]; 328 synchronized (sListeners) { 329 if (sensor == -1 || sListeners.isEmpty()) { 330 if (sensor == -1) { 331 // we lost the connection to the event stream. this happens 332 // when the last listener is removed. 333 Log.d(TAG, "_sensors_data_poll() failed, we bail out."); 334 } 335 336 // we have no more listeners or polling failed, terminate the thread 337 sensors_data_close(); 338 mThread = null; 339 break; 340 } 341 final Sensor sensorObject = sHandleToSensor.get(sensor); 342 if (sensorObject != null) { 343 // report the sensor event to all listeners that 344 // care about it. 345 final int size = sListeners.size(); 346 for (int i=0 ; i<size ; i++) { 347 ListenerDelegate listener = sListeners.get(i); 348 if (listener.hasSensor(sensorObject)) { 349 // this is asynchronous (okay to call 350 // with sListeners lock held). 351 listener.onSensorChangedLocked(sensorObject, 352 values, timestamp, accuracy); 353 } 354 } 355 } 356 } 357 } 358 //Log.d(TAG, "exiting main sensor thread"); 359 } 360 } 361 } 362 363 /*-----------------------------------------------------------------------*/ 364 365 private class ListenerDelegate extends Binder { 366 final SensorEventListener mSensorEventListener; 367 private final ArrayList<Sensor> mSensorList = new ArrayList<Sensor>(); 368 private final Handler mHandler; 369 private SensorEvent mValuesPool; 370 public int mSensors; 371 372 ListenerDelegate(SensorEventListener listener, Sensor sensor, Handler handler) { 373 mSensorEventListener = listener; 374 Looper looper = (handler != null) ? handler.getLooper() : mMainLooper; 375 // currently we create one Handler instance per listener, but we could 376 // have one per looper (we'd need to pass the ListenerDelegate 377 // instance to handleMessage and keep track of them separately). 378 mHandler = new Handler(looper) { 379 @Override 380 public void handleMessage(Message msg) { 381 SensorEvent t = (SensorEvent)msg.obj; 382 if (t.accuracy >= 0) { 383 mSensorEventListener.onAccuracyChanged(t.sensor, t.accuracy); 384 } 385 mSensorEventListener.onSensorChanged(t); 386 returnToPool(t); 387 } 388 }; 389 addSensor(sensor); 390 } 391 392 protected SensorEvent createSensorEvent() { 393 // maximal size for all legacy events is 3 394 return new SensorEvent(3); 395 } 396 397 protected SensorEvent getFromPool() { 398 SensorEvent t = null; 399 synchronized (this) { 400 // remove the array from the pool 401 t = mValuesPool; 402 mValuesPool = null; 403 } 404 if (t == null) { 405 // the pool was empty, we need a new one 406 t = createSensorEvent(); 407 } 408 return t; 409 } 410 411 protected void returnToPool(SensorEvent t) { 412 synchronized (this) { 413 // put back the array into the pool 414 if (mValuesPool == null) { 415 mValuesPool = t; 416 } 417 } 418 } 419 420 Object getListener() { 421 return mSensorEventListener; 422 } 423 424 int addSensor(Sensor sensor) { 425 mSensors |= 1<<sensor.getHandle(); 426 mSensorList.add(sensor); 427 return mSensors; 428 } 429 int removeSensor(Sensor sensor) { 430 mSensors &= ~(1<<sensor.getHandle()); 431 mSensorList.remove(sensor); 432 return mSensors; 433 } 434 boolean hasSensor(Sensor sensor) { 435 return ((mSensors & (1<<sensor.getHandle())) != 0); 436 } 437 List<Sensor> getSensors() { 438 return mSensorList; 439 } 440 441 void onSensorChangedLocked(Sensor sensor, float[] values, long[] timestamp, int accuracy) { 442 SensorEvent t = getFromPool(); 443 final float[] v = t.values; 444 v[0] = values[0]; 445 v[1] = values[1]; 446 v[2] = values[2]; 447 t.timestamp = timestamp[0]; 448 t.accuracy = accuracy; 449 t.sensor = sensor; 450 Message msg = Message.obtain(); 451 msg.what = 0; 452 msg.obj = t; 453 mHandler.sendMessage(msg); 454 } 455 } 456 457 /** 458 * {@hide} 459 */ 460 public SensorManager(Looper mainLooper) { 461 mSensorService = ISensorService.Stub.asInterface( 462 ServiceManager.getService(Context.SENSOR_SERVICE)); 463 mMainLooper = mainLooper; 464 465 466 synchronized(sListeners) { 467 if (!sSensorModuleInitialized) { 468 sSensorModuleInitialized = true; 469 470 nativeClassInit(); 471 472 sWindowManager = IWindowManager.Stub.asInterface( 473 ServiceManager.getService("window")); 474 if (sWindowManager != null) { 475 // if it's null we're running in the system process 476 // which won't get the rotated values 477 try { 478 sRotation = sWindowManager.watchRotation(this); 479 } catch (RemoteException e) { 480 } 481 } 482 483 // initialize the sensor list 484 sensors_module_init(); 485 final ArrayList<Sensor> fullList = sFullSensorsList; 486 int i = 0; 487 do { 488 Sensor sensor = new Sensor(); 489 i = sensors_module_get_next_sensor(sensor, i); 490 491 if (i>=0) { 492 Log.d(TAG, "found sensor: " + sensor.getName() + 493 ", handle=" + sensor.getHandle()); 494 sensor.setLegacyType(getLegacySensorType(sensor.getType())); 495 fullList.add(sensor); 496 sHandleToSensor.append(sensor.getHandle(), sensor); 497 } 498 } while (i>0); 499 500 sSensorThread = new SensorThread(); 501 } 502 } 503 } 504 505 private int getLegacySensorType(int type) { 506 switch (type) { 507 case Sensor.TYPE_ACCELEROMETER: 508 return SENSOR_ACCELEROMETER; 509 case Sensor.TYPE_MAGNETIC_FIELD: 510 return SENSOR_MAGNETIC_FIELD; 511 case Sensor.TYPE_ORIENTATION: 512 return SENSOR_ORIENTATION_RAW; 513 case Sensor.TYPE_TEMPERATURE: 514 return SENSOR_TEMPERATURE; 515 } 516 return 0; 517 } 518 519 /** @return available sensors. 520 * @deprecated This method is deprecated, use 521 * {@link SensorManager#getSensorList(int)} instead 522 */ 523 @Deprecated 524 public int getSensors() { 525 int result = 0; 526 final ArrayList<Sensor> fullList = sFullSensorsList; 527 for (Sensor i : fullList) { 528 switch (i.getType()) { 529 case Sensor.TYPE_ACCELEROMETER: 530 result |= SensorManager.SENSOR_ACCELEROMETER; 531 break; 532 case Sensor.TYPE_MAGNETIC_FIELD: 533 result |= SensorManager.SENSOR_MAGNETIC_FIELD; 534 break; 535 case Sensor.TYPE_ORIENTATION: 536 result |= SensorManager.SENSOR_ORIENTATION | 537 SensorManager.SENSOR_ORIENTATION_RAW; 538 break; 539 } 540 } 541 return result; 542 } 543 544 /** 545 * Use this method to get the list of available sensors of a certain 546 * type. Make multiple calls to get sensors of different types or use 547 * {@link android.hardware.Sensor#TYPE_ALL Sensor.TYPE_ALL} to get all 548 * the sensors. 549 * 550 * @param type of sensors requested 551 * @return a list of sensors matching the asked type. 552 */ 553 public List<Sensor> getSensorList(int type) { 554 // cache the returned lists the first time 555 List<Sensor> list; 556 final ArrayList<Sensor> fullList = sFullSensorsList; 557 synchronized(fullList) { 558 list = sSensorListByType.get(type); 559 if (list == null) { 560 if (type == Sensor.TYPE_ALL) { 561 list = fullList; 562 } else { 563 list = new ArrayList<Sensor>(); 564 for (Sensor i : fullList) { 565 if (i.getType() == type) 566 list.add(i); 567 } 568 } 569 list = Collections.unmodifiableList(list); 570 sSensorListByType.append(type, list); 571 } 572 } 573 return list; 574 } 575 576 /** 577 * Use this method to get the default sensor for a given type. Note that 578 * the returned sensor could be a composite sensor, and its data could be 579 * averaged or filtered. If you need to access the raw sensors use 580 * {@link SensorManager#getSensorList(int) getSensorList}. 581 * 582 * 583 * @param type of sensors requested 584 * @return the default sensors matching the asked type. 585 */ 586 public Sensor getDefaultSensor(int type) { 587 // TODO: need to be smarter, for now, just return the 1st sensor 588 List<Sensor> l = getSensorList(type); 589 return l.isEmpty() ? null : l.get(0); 590 } 591 592 593 /** 594 * Registers a listener for given sensors. 595 * @deprecated This method is deprecated, use 596 * {@link SensorManager#registerListener(SensorEventListener, Sensor, int)} 597 * instead. 598 * 599 * @param listener sensor listener object 600 * @param sensors a bit masks of the sensors to register to 601 * 602 * @return true if the sensor is supported and successfully enabled 603 */ 604 @Deprecated 605 public boolean registerListener(SensorListener listener, int sensors) { 606 return registerListener(listener, sensors, SENSOR_DELAY_NORMAL); 607 } 608 609 /** 610 * Registers a SensorListener for given sensors. 611 * @deprecated This method is deprecated, use 612 * {@link SensorManager#registerListener(SensorEventListener, Sensor, int)} 613 * instead. 614 * 615 * @param listener sensor listener object 616 * @param sensors a bit masks of the sensors to register to 617 * @param rate rate of events. This is only a hint to the system. events 618 * may be received faster or slower than the specified rate. Usually events 619 * are received faster. The value must be one of {@link #SENSOR_DELAY_NORMAL}, 620 * {@link #SENSOR_DELAY_UI}, {@link #SENSOR_DELAY_GAME}, or {@link #SENSOR_DELAY_FASTEST}. 621 * 622 * @return true if the sensor is supported and successfully enabled 623 */ 624 @Deprecated 625 public boolean registerListener(SensorListener listener, int sensors, int rate) { 626 if (listener == null) { 627 return false; 628 } 629 boolean result = false; 630 result = registerLegacyListener(SENSOR_ACCELEROMETER, Sensor.TYPE_ACCELEROMETER, 631 listener, sensors, rate) || result; 632 result = registerLegacyListener(SENSOR_MAGNETIC_FIELD, Sensor.TYPE_MAGNETIC_FIELD, 633 listener, sensors, rate) || result; 634 result = registerLegacyListener(SENSOR_ORIENTATION_RAW, Sensor.TYPE_ORIENTATION, 635 listener, sensors, rate) || result; 636 result = registerLegacyListener(SENSOR_ORIENTATION, Sensor.TYPE_ORIENTATION, 637 listener, sensors, rate) || result; 638 result = registerLegacyListener(SENSOR_TEMPERATURE, Sensor.TYPE_TEMPERATURE, 639 listener, sensors, rate) || result; 640 return result; 641 } 642 643 @SuppressWarnings("deprecation") 644 private boolean registerLegacyListener(int legacyType, int type, 645 SensorListener listener, int sensors, int rate) 646 { 647 if (listener == null) { 648 return false; 649 } 650 boolean result = false; 651 // Are we activating this legacy sensor? 652 if ((sensors & legacyType) != 0) { 653 // if so, find a suitable Sensor 654 Sensor sensor = getDefaultSensor(type); 655 if (sensor != null) { 656 // If we don't already have one, create a LegacyListener 657 // to wrap this listener and process the events as 658 // they are expected by legacy apps. 659 LegacyListener legacyListener = null; 660 synchronized (mLegacyListenersMap) { 661 legacyListener = mLegacyListenersMap.get(listener); 662 if (legacyListener == null) { 663 // we didn't find a LegacyListener for this client, 664 // create one, and put it in our list. 665 legacyListener = new LegacyListener(listener); 666 mLegacyListenersMap.put(listener, legacyListener); 667 } 668 } 669 // register this legacy sensor with this legacy listener 670 legacyListener.registerSensor(legacyType); 671 // and finally, register the legacy listener with the new apis 672 result = registerListener(legacyListener, sensor, rate); 673 } 674 } 675 return result; 676 } 677 678 /** 679 * Unregisters a listener for the sensors with which it is registered. 680 * @deprecated This method is deprecated, use 681 * {@link SensorManager#unregisterListener(SensorEventListener, Sensor)} 682 * instead. 683 * 684 * @param listener a SensorListener object 685 * @param sensors a bit masks of the sensors to unregister from 686 */ 687 @Deprecated 688 public void unregisterListener(SensorListener listener, int sensors) { 689 unregisterLegacyListener(SENSOR_ACCELEROMETER, Sensor.TYPE_ACCELEROMETER, 690 listener, sensors); 691 unregisterLegacyListener(SENSOR_MAGNETIC_FIELD, Sensor.TYPE_MAGNETIC_FIELD, 692 listener, sensors); 693 unregisterLegacyListener(SENSOR_ORIENTATION_RAW, Sensor.TYPE_ORIENTATION, 694 listener, sensors); 695 unregisterLegacyListener(SENSOR_ORIENTATION, Sensor.TYPE_ORIENTATION, 696 listener, sensors); 697 unregisterLegacyListener(SENSOR_TEMPERATURE, Sensor.TYPE_TEMPERATURE, 698 listener, sensors); 699 } 700 701 @SuppressWarnings("deprecation") 702 private void unregisterLegacyListener(int legacyType, int type, 703 SensorListener listener, int sensors) 704 { 705 if (listener == null) { 706 return; 707 } 708 // do we know about this listener? 709 LegacyListener legacyListener = null; 710 synchronized (mLegacyListenersMap) { 711 legacyListener = mLegacyListenersMap.get(listener); 712 } 713 if (legacyListener != null) { 714 // Are we deactivating this legacy sensor? 715 if ((sensors & legacyType) != 0) { 716 // if so, find the corresponding Sensor 717 Sensor sensor = getDefaultSensor(type); 718 if (sensor != null) { 719 // unregister this legacy sensor and if we don't 720 // need the corresponding Sensor, unregister it too 721 if (legacyListener.unregisterSensor(legacyType)) { 722 // corresponding sensor not needed, unregister 723 unregisterListener(legacyListener, sensor); 724 // finally check if we still need the legacyListener 725 // in our mapping, if not, get rid of it too. 726 synchronized(sListeners) { 727 boolean found = false; 728 for (ListenerDelegate i : sListeners) { 729 if (i.getListener() == legacyListener) { 730 found = true; 731 break; 732 } 733 } 734 if (!found) { 735 synchronized (mLegacyListenersMap) { 736 mLegacyListenersMap.remove(listener); 737 } 738 } 739 } 740 } 741 } 742 } 743 } 744 } 745 746 /** 747 * Unregisters a listener for all sensors. 748 * @deprecated This method is deprecated, use 749 * {@link SensorManager#unregisterListener(SensorEventListener)} 750 * instead. 751 * 752 * @param listener a SensorListener object 753 */ 754 @Deprecated 755 public void unregisterListener(SensorListener listener) { 756 unregisterListener(listener, SENSOR_ALL | SENSOR_ORIENTATION_RAW); 757 } 758 759 /** 760 * Unregisters a listener for the sensors with which it is registered. 761 * 762 * @param listener a SensorEventListener object 763 * @param sensor the sensor to unregister from 764 * 765 */ 766 public void unregisterListener(SensorEventListener listener, Sensor sensor) { 767 unregisterListener((Object)listener, sensor); 768 } 769 770 /** 771 * Unregisters a listener for all sensors. 772 * 773 * @param listener a SensorListener object 774 * 775 */ 776 public void unregisterListener(SensorEventListener listener) { 777 unregisterListener((Object)listener); 778 } 779 780 781 /** 782 * Registers a {@link android.hardware.SensorEventListener SensorEventListener} 783 * for the given sensor. 784 * 785 * @param listener A {@link android.hardware.SensorEventListener SensorEventListener} object. 786 * @param sensor The {@link android.hardware.Sensor Sensor} to register to. 787 * @param rate The rate {@link android.hardware.SensorEvent sensor events} are delivered at. 788 * This is only a hint to the system. Events may be received faster or 789 * slower than the specified rate. Usually events are received faster. The value must be 790 * one of {@link #SENSOR_DELAY_NORMAL}, {@link #SENSOR_DELAY_UI}, {@link #SENSOR_DELAY_GAME}, 791 * or {@link #SENSOR_DELAY_FASTEST}. 792 * 793 * @return true if the sensor is supported and successfully enabled. 794 * 795 */ 796 public boolean registerListener(SensorEventListener listener, Sensor sensor, int rate) { 797 return registerListener(listener, sensor, rate, null); 798 } 799 800 /** 801 * Registers a {@link android.hardware.SensorEventListener SensorEventListener} 802 * for the given sensor. 803 * 804 * @param listener A {@link android.hardware.SensorEventListener SensorEventListener} object. 805 * @param sensor The {@link android.hardware.Sensor Sensor} to register to. 806 * @param rate The rate {@link android.hardware.SensorEvent sensor events} are delivered at. 807 * This is only a hint to the system. Events may be received faster or 808 * slower than the specified rate. Usually events are received faster. The value must be one 809 * of {@link #SENSOR_DELAY_NORMAL}, {@link #SENSOR_DELAY_UI}, {@link #SENSOR_DELAY_GAME}, or 810 * {@link #SENSOR_DELAY_FASTEST}. 811 * @param handler The {@link android.os.Handler Handler} the 812 * {@link android.hardware.SensorEvent sensor events} will be delivered to. 813 * 814 * @return true if the sensor is supported and successfully enabled. 815 * 816 */ 817 public boolean registerListener(SensorEventListener listener, Sensor sensor, int rate, 818 Handler handler) { 819 if (listener == null || sensor == null) { 820 return false; 821 } 822 boolean result; 823 int delay = -1; 824 switch (rate) { 825 case SENSOR_DELAY_FASTEST: 826 delay = 0; 827 break; 828 case SENSOR_DELAY_GAME: 829 delay = 20; 830 break; 831 case SENSOR_DELAY_UI: 832 delay = 60; 833 break; 834 case SENSOR_DELAY_NORMAL: 835 delay = 200; 836 break; 837 default: 838 return false; 839 } 840 841 try { 842 synchronized (sListeners) { 843 ListenerDelegate l = null; 844 for (ListenerDelegate i : sListeners) { 845 if (i.getListener() == listener) { 846 l = i; 847 break; 848 } 849 } 850 851 String name = sensor.getName(); 852 int handle = sensor.getHandle(); 853 if (l == null) { 854 l = new ListenerDelegate(listener, sensor, handler); 855 result = mSensorService.enableSensor(l, name, handle, delay); 856 if (result) { 857 sListeners.add(l); 858 sListeners.notify(); 859 } 860 if (!sListeners.isEmpty()) { 861 sSensorThread.startLocked(mSensorService); 862 } 863 } else { 864 result = mSensorService.enableSensor(l, name, handle, delay); 865 if (result) { 866 l.addSensor(sensor); 867 } 868 } 869 } 870 } catch (RemoteException e) { 871 Log.e(TAG, "RemoteException in registerListener: ", e); 872 result = false; 873 } 874 return result; 875 } 876 877 private void unregisterListener(Object listener, Sensor sensor) { 878 if (listener == null || sensor == null) { 879 return; 880 } 881 try { 882 synchronized (sListeners) { 883 final int size = sListeners.size(); 884 for (int i=0 ; i<size ; i++) { 885 ListenerDelegate l = sListeners.get(i); 886 if (l.getListener() == listener) { 887 // disable these sensors 888 String name = sensor.getName(); 889 int handle = sensor.getHandle(); 890 mSensorService.enableSensor(l, name, handle, SENSOR_DISABLE); 891 // if we have no more sensors enabled on this listener, 892 // take it off the list. 893 if (l.removeSensor(sensor) == 0) { 894 sListeners.remove(i); 895 } 896 break; 897 } 898 } 899 } 900 } catch (RemoteException e) { 901 Log.e(TAG, "RemoteException in unregisterListener: ", e); 902 } 903 } 904 905 private void unregisterListener(Object listener) { 906 if (listener == null) { 907 return; 908 } 909 try { 910 synchronized (sListeners) { 911 final int size = sListeners.size(); 912 for (int i=0 ; i<size ; i++) { 913 ListenerDelegate l = sListeners.get(i); 914 if (l.getListener() == listener) { 915 // disable all sensors for this listener 916 for (Sensor sensor : l.getSensors()) { 917 String name = sensor.getName(); 918 int handle = sensor.getHandle(); 919 mSensorService.enableSensor(l, name, handle, SENSOR_DISABLE); 920 } 921 sListeners.remove(i); 922 break; 923 } 924 } 925 } 926 } catch (RemoteException e) { 927 Log.e(TAG, "RemoteException in unregisterListener: ", e); 928 } 929 } 930 931 /** 932 * Computes the inclination matrix <b>I</b> as well as the rotation 933 * matrix <b>R</b> transforming a vector from the 934 * device coordinate system to the world's coordinate system which is 935 * defined as a direct orthonormal basis, where: 936 * 937 * <li>X is defined as the vector product <b>Y.Z</b> (It is tangential to 938 * the ground at the device's current location and roughly points East).</li> 939 * <li>Y is tangential to the ground at the device's current location and 940 * points towards the magnetic North Pole.</li> 941 * <li>Z points towards the sky and is perpendicular to the ground.</li> 942 * <p> 943 * <hr> 944 * <p>By definition: 945 * <p>[0 0 g] = <b>R</b> * <b>gravity</b> (g = magnitude of gravity) 946 * <p>[0 m 0] = <b>I</b> * <b>R</b> * <b>geomagnetic</b> 947 * (m = magnitude of geomagnetic field) 948 * <p><b>R</b> is the identity matrix when the device is aligned with the 949 * world's coordinate system, that is, when the device's X axis points 950 * toward East, the Y axis points to the North Pole and the device is facing 951 * the sky. 952 * 953 * <p><b>I</b> is a rotation matrix transforming the geomagnetic 954 * vector into the same coordinate space as gravity (the world's coordinate 955 * space). <b>I</b> is a simple rotation around the X axis. 956 * The inclination angle in radians can be computed with 957 * {@link #getInclination}. 958 * <hr> 959 * 960 * <p> Each matrix is returned either as a 3x3 or 4x4 row-major matrix 961 * depending on the length of the passed array: 962 * <p><u>If the array length is 16:</u> 963 * <pre> 964 * / M[ 0] M[ 1] M[ 2] M[ 3] \ 965 * | M[ 4] M[ 5] M[ 6] M[ 7] | 966 * | M[ 8] M[ 9] M[10] M[11] | 967 * \ M[12] M[13] M[14] M[15] / 968 *</pre> 969 * This matrix is ready to be used by OpenGL ES's 970 * {@link javax.microedition.khronos.opengles.GL10#glLoadMatrixf(float[], int) 971 * glLoadMatrixf(float[], int)}. 972 * <p>Note that because OpenGL matrices are column-major matrices you must 973 * transpose the matrix before using it. However, since the matrix is a 974 * rotation matrix, its transpose is also its inverse, conveniently, it is 975 * often the inverse of the rotation that is needed for rendering; it can 976 * therefore be used with OpenGL ES directly. 977 * <p> 978 * Also note that the returned matrices always have this form: 979 * <pre> 980 * / M[ 0] M[ 1] M[ 2] 0 \ 981 * | M[ 4] M[ 5] M[ 6] 0 | 982 * | M[ 8] M[ 9] M[10] 0 | 983 * \ 0 0 0 1 / 984 *</pre> 985 * <p><u>If the array length is 9:</u> 986 * <pre> 987 * / M[ 0] M[ 1] M[ 2] \ 988 * | M[ 3] M[ 4] M[ 5] | 989 * \ M[ 6] M[ 7] M[ 8] / 990 *</pre> 991 * 992 * <hr> 993 * <p>The inverse of each matrix can be computed easily by taking its 994 * transpose. 995 * 996 * <p>The matrices returned by this function are meaningful only when the 997 * device is not free-falling and it is not close to the magnetic north. 998 * If the device is accelerating, or placed into a strong magnetic field, 999 * the returned matrices may be inaccurate. 1000 * 1001 * @param R is an array of 9 floats holding the rotation matrix <b>R</b> 1002 * when this function returns. R can be null.<p> 1003 * @param I is an array of 9 floats holding the rotation matrix <b>I</b> 1004 * when this function returns. I can be null.<p> 1005 * @param gravity is an array of 3 floats containing the gravity vector 1006 * expressed in the device's coordinate. You can simply use the 1007 * {@link android.hardware.SensorEvent#values values} 1008 * returned by a {@link android.hardware.SensorEvent SensorEvent} of a 1009 * {@link android.hardware.Sensor Sensor} of type 1010 * {@link android.hardware.Sensor#TYPE_ACCELEROMETER TYPE_ACCELEROMETER}.<p> 1011 * @param geomagnetic is an array of 3 floats containing the geomagnetic 1012 * vector expressed in the device's coordinate. You can simply use the 1013 * {@link android.hardware.SensorEvent#values values} 1014 * returned by a {@link android.hardware.SensorEvent SensorEvent} of a 1015 * {@link android.hardware.Sensor Sensor} of type 1016 * {@link android.hardware.Sensor#TYPE_MAGNETIC_FIELD TYPE_MAGNETIC_FIELD}. 1017 * @return 1018 * true on success<p> 1019 * false on failure (for instance, if the device is in free fall). 1020 * On failure the output matrices are not modified. 1021 */ 1022 1023 public static boolean getRotationMatrix(float[] R, float[] I, 1024 float[] gravity, float[] geomagnetic) { 1025 // TODO: move this to native code for efficiency 1026 float Ax = gravity[0]; 1027 float Ay = gravity[1]; 1028 float Az = gravity[2]; 1029 final float Ex = geomagnetic[0]; 1030 final float Ey = geomagnetic[1]; 1031 final float Ez = geomagnetic[2]; 1032 float Hx = Ey*Az - Ez*Ay; 1033 float Hy = Ez*Ax - Ex*Az; 1034 float Hz = Ex*Ay - Ey*Ax; 1035 final float normH = (float)Math.sqrt(Hx*Hx + Hy*Hy + Hz*Hz); 1036 if (normH < 0.1f) { 1037 // device is close to free fall (or in space?), or close to 1038 // magnetic north pole. Typical values are > 100. 1039 return false; 1040 } 1041 final float invH = 1.0f / normH; 1042 Hx *= invH; 1043 Hy *= invH; 1044 Hz *= invH; 1045 final float invA = 1.0f / (float)Math.sqrt(Ax*Ax + Ay*Ay + Az*Az); 1046 Ax *= invA; 1047 Ay *= invA; 1048 Az *= invA; 1049 final float Mx = Ay*Hz - Az*Hy; 1050 final float My = Az*Hx - Ax*Hz; 1051 final float Mz = Ax*Hy - Ay*Hx; 1052 if (R != null) { 1053 if (R.length == 9) { 1054 R[0] = Hx; R[1] = Hy; R[2] = Hz; 1055 R[3] = Mx; R[4] = My; R[5] = Mz; 1056 R[6] = Ax; R[7] = Ay; R[8] = Az; 1057 } else if (R.length == 16) { 1058 R[0] = Hx; R[1] = Hy; R[2] = Hz; R[3] = 0; 1059 R[4] = Mx; R[5] = My; R[6] = Mz; R[7] = 0; 1060 R[8] = Ax; R[9] = Ay; R[10] = Az; R[11] = 0; 1061 R[12] = 0; R[13] = 0; R[14] = 0; R[15] = 1; 1062 } 1063 } 1064 if (I != null) { 1065 // compute the inclination matrix by projecting the geomagnetic 1066 // vector onto the Z (gravity) and X (horizontal component 1067 // of geomagnetic vector) axes. 1068 final float invE = 1.0f / (float)Math.sqrt(Ex*Ex + Ey*Ey + Ez*Ez); 1069 final float c = (Ex*Mx + Ey*My + Ez*Mz) * invE; 1070 final float s = (Ex*Ax + Ey*Ay + Ez*Az) * invE; 1071 if (I.length == 9) { 1072 I[0] = 1; I[1] = 0; I[2] = 0; 1073 I[3] = 0; I[4] = c; I[5] = s; 1074 I[6] = 0; I[7] =-s; I[8] = c; 1075 } else if (I.length == 16) { 1076 I[0] = 1; I[1] = 0; I[2] = 0; 1077 I[4] = 0; I[5] = c; I[6] = s; 1078 I[8] = 0; I[9] =-s; I[10]= c; 1079 I[3] = I[7] = I[11] = I[12] = I[13] = I[14] = 0; 1080 I[15] = 1; 1081 } 1082 } 1083 return true; 1084 } 1085 1086 /** 1087 * Computes the geomagnetic inclination angle in radians from the 1088 * inclination matrix <b>I</b> returned by {@link #getRotationMatrix}. 1089 * @param I inclination matrix see {@link #getRotationMatrix}. 1090 * @return The geomagnetic inclination angle in radians. 1091 */ 1092 public static float getInclination(float[] I) { 1093 if (I.length == 9) { 1094 return (float)Math.atan2(I[5], I[4]); 1095 } else { 1096 return (float)Math.atan2(I[6], I[5]); 1097 } 1098 } 1099 1100 /** 1101 * Rotates the supplied rotation matrix so it is expressed in a 1102 * different coordinate system. This is typically used when an application 1103 * needs to compute the three orientation angles of the device (see 1104 * {@link #getOrientation}) in a different coordinate system. 1105 * 1106 * <p>When the rotation matrix is used for drawing (for instance with 1107 * OpenGL ES), it usually <b>doesn't need</b> to be transformed by this 1108 * function, unless the screen is physically rotated, such as when used 1109 * in landscape mode. 1110 * 1111 * <p><u>Examples:</u><p> 1112 * 1113 * <li>Using the camera (Y axis along the camera's axis) for an augmented 1114 * reality application where the rotation angles are needed :</li><p> 1115 * 1116 * <code>remapCoordinateSystem(inR, AXIS_X, AXIS_Z, outR);</code><p> 1117 * 1118 * <li>Using the device as a mechanical compass in landscape mode:</li><p> 1119 * 1120 * <code>remapCoordinateSystem(inR, AXIS_Y, AXIS_MINUS_X, outR);</code><p> 1121 * 1122 * Beware of the above example. This call is needed only if the device is 1123 * physically used in landscape mode to calculate the rotation angles (see 1124 * {@link #getOrientation}). 1125 * If the rotation matrix is also used for rendering, it may not need to 1126 * be transformed, for instance if your {@link android.app.Activity 1127 * Activity} is running in landscape mode. 1128 * 1129 * <p>Since the resulting coordinate system is orthonormal, only two axes 1130 * need to be specified. 1131 * 1132 * @param inR the rotation matrix to be transformed. Usually it is the 1133 * matrix returned by {@link #getRotationMatrix}. 1134 * @param X defines on which world axis and direction the X axis of the 1135 * device is mapped. 1136 * @param Y defines on which world axis and direction the Y axis of the 1137 * device is mapped. 1138 * @param outR the transformed rotation matrix. inR and outR can be the same 1139 * array, but it is not recommended for performance reason. 1140 * @return true on success. false if the input parameters are incorrect, for 1141 * instance if X and Y define the same axis. Or if inR and outR don't have 1142 * the same length. 1143 */ 1144 1145 public static boolean remapCoordinateSystem(float[] inR, int X, int Y, 1146 float[] outR) 1147 { 1148 if (inR == outR) { 1149 final float[] temp = mTempMatrix; 1150 synchronized(temp) { 1151 // we don't expect to have a lot of contention 1152 if (remapCoordinateSystemImpl(inR, X, Y, temp)) { 1153 final int size = outR.length; 1154 for (int i=0 ; i<size ; i++) 1155 outR[i] = temp[i]; 1156 return true; 1157 } 1158 } 1159 } 1160 return remapCoordinateSystemImpl(inR, X, Y, outR); 1161 } 1162 1163 private static boolean remapCoordinateSystemImpl(float[] inR, int X, int Y, 1164 float[] outR) 1165 { 1166 /* 1167 * X and Y define a rotation matrix 'r': 1168 * 1169 * (X==1)?((X&0x80)?-1:1):0 (X==2)?((X&0x80)?-1:1):0 (X==3)?((X&0x80)?-1:1):0 1170 * (Y==1)?((Y&0x80)?-1:1):0 (Y==2)?((Y&0x80)?-1:1):0 (Y==3)?((X&0x80)?-1:1):0 1171 * r[0] ^ r[1] 1172 * 1173 * where the 3rd line is the vector product of the first 2 lines 1174 * 1175 */ 1176 1177 final int length = outR.length; 1178 if (inR.length != length) 1179 return false; // invalid parameter 1180 if ((X & 0x7C)!=0 || (Y & 0x7C)!=0) 1181 return false; // invalid parameter 1182 if (((X & 0x3)==0) || ((Y & 0x3)==0)) 1183 return false; // no axis specified 1184 if ((X & 0x3) == (Y & 0x3)) 1185 return false; // same axis specified 1186 1187 // Z is "the other" axis, its sign is either +/- sign(X)*sign(Y) 1188 // this can be calculated by exclusive-or'ing X and Y; except for 1189 // the sign inversion (+/-) which is calculated below. 1190 int Z = X ^ Y; 1191 1192 // extract the axis (remove the sign), offset in the range 0 to 2. 1193 final int x = (X & 0x3)-1; 1194 final int y = (Y & 0x3)-1; 1195 final int z = (Z & 0x3)-1; 1196 1197 // compute the sign of Z (whether it needs to be inverted) 1198 final int axis_y = (z+1)%3; 1199 final int axis_z = (z+2)%3; 1200 if (((x^axis_y)|(y^axis_z)) != 0) 1201 Z ^= 0x80; 1202 1203 final boolean sx = (X>=0x80); 1204 final boolean sy = (Y>=0x80); 1205 final boolean sz = (Z>=0x80); 1206 1207 // Perform R * r, in avoiding actual muls and adds. 1208 final int rowLength = ((length==16)?4:3); 1209 for (int j=0 ; j<3 ; j++) { 1210 final int offset = j*rowLength; 1211 for (int i=0 ; i<3 ; i++) { 1212 if (x==i) outR[offset+i] = sx ? -inR[offset+0] : inR[offset+0]; 1213 if (y==i) outR[offset+i] = sy ? -inR[offset+1] : inR[offset+1]; 1214 if (z==i) outR[offset+i] = sz ? -inR[offset+2] : inR[offset+2]; 1215 } 1216 } 1217 if (length == 16) { 1218 outR[3] = outR[7] = outR[11] = outR[12] = outR[13] = outR[14] = 0; 1219 outR[15] = 1; 1220 } 1221 return true; 1222 } 1223 1224 /** 1225 * Computes the device's orientation based on the rotation matrix. 1226 * <p> When it returns, the array values is filled with the result: 1227 * <li>values[0]: <i>azimuth</i>, rotation around the Z axis.</li> 1228 * <li>values[1]: <i>pitch</i>, rotation around the X axis.</li> 1229 * <li>values[2]: <i>roll</i>, rotation around the Y axis.</li> 1230 * <p> 1231 * 1232 * @param R rotation matrix see {@link #getRotationMatrix}. 1233 * @param values an array of 3 floats to hold the result. 1234 * @return The array values passed as argument. 1235 */ 1236 public static float[] getOrientation(float[] R, float values[]) { 1237 /* 1238 * 4x4 (length=16) case: 1239 * / R[ 0] R[ 1] R[ 2] 0 \ 1240 * | R[ 4] R[ 5] R[ 6] 0 | 1241 * | R[ 8] R[ 9] R[10] 0 | 1242 * \ 0 0 0 1 / 1243 * 1244 * 3x3 (length=9) case: 1245 * / R[ 0] R[ 1] R[ 2] \ 1246 * | R[ 3] R[ 4] R[ 5] | 1247 * \ R[ 6] R[ 7] R[ 8] / 1248 * 1249 */ 1250 if (R.length == 9) { 1251 values[0] = (float)Math.atan2(R[1], R[4]); 1252 values[1] = (float)Math.asin(-R[7]); 1253 values[2] = (float)Math.atan2(-R[6], R[8]); 1254 } else { 1255 values[0] = (float)Math.atan2(R[1], R[5]); 1256 values[1] = (float)Math.asin(-R[9]); 1257 values[2] = (float)Math.atan2(-R[8], R[10]); 1258 } 1259 return values; 1260 } 1261 1262 1263 /** 1264 * {@hide} 1265 */ 1266 public void onRotationChanged(int rotation) { 1267 synchronized(sListeners) { 1268 sRotation = rotation; 1269 } 1270 } 1271 1272 static int getRotation() { 1273 synchronized(sListeners) { 1274 return sRotation; 1275 } 1276 } 1277 1278 private class LegacyListener implements SensorEventListener { 1279 private float mValues[] = new float[6]; 1280 @SuppressWarnings("deprecation") 1281 private SensorListener mTarget; 1282 private int mSensors; 1283 private final LmsFilter mYawfilter = new LmsFilter(); 1284 1285 @SuppressWarnings("deprecation") 1286 LegacyListener(SensorListener target) { 1287 mTarget = target; 1288 mSensors = 0; 1289 } 1290 1291 void registerSensor(int legacyType) { 1292 mSensors |= legacyType; 1293 } 1294 1295 boolean unregisterSensor(int legacyType) { 1296 mSensors &= ~legacyType; 1297 int mask = SENSOR_ORIENTATION|SENSOR_ORIENTATION_RAW; 1298 if (((legacyType&mask)!=0) && ((mSensors&mask)!=0)) { 1299 return false; 1300 } 1301 return true; 1302 } 1303 1304 @SuppressWarnings("deprecation") 1305 public void onAccuracyChanged(Sensor sensor, int accuracy) { 1306 try { 1307 mTarget.onAccuracyChanged(sensor.getLegacyType(), accuracy); 1308 } catch (AbstractMethodError e) { 1309 // old app that doesn't implement this method 1310 // just ignore it. 1311 } 1312 } 1313 1314 @SuppressWarnings("deprecation") 1315 public void onSensorChanged(SensorEvent event) { 1316 final float v[] = mValues; 1317 v[0] = event.values[0]; 1318 v[1] = event.values[1]; 1319 v[2] = event.values[2]; 1320 int legacyType = event.sensor.getLegacyType(); 1321 mapSensorDataToWindow(legacyType, v, SensorManager.getRotation()); 1322 if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) { 1323 if ((mSensors & SENSOR_ORIENTATION_RAW)!=0) { 1324 mTarget.onSensorChanged(SENSOR_ORIENTATION_RAW, v); 1325 } 1326 if ((mSensors & SENSOR_ORIENTATION)!=0) { 1327 v[0] = mYawfilter.filter(event.timestamp, v[0]); 1328 mTarget.onSensorChanged(SENSOR_ORIENTATION, v); 1329 } 1330 } else { 1331 mTarget.onSensorChanged(legacyType, v); 1332 } 1333 } 1334 1335 /* 1336 * Helper function to convert the specified sensor's data to the windows's 1337 * coordinate space from the device's coordinate space. 1338 * 1339 * output: 3,4,5: values in the old API format 1340 * 0,1,2: transformed values in the old API format 1341 * 1342 */ 1343 private void mapSensorDataToWindow(int sensor, 1344 float[] values, int orientation) { 1345 float x = values[0]; 1346 float y = values[1]; 1347 float z = values[2]; 1348 1349 switch (sensor) { 1350 case SensorManager.SENSOR_ORIENTATION: 1351 case SensorManager.SENSOR_ORIENTATION_RAW: 1352 z = -z; 1353 break; 1354 case SensorManager.SENSOR_ACCELEROMETER: 1355 x = -x; 1356 y = -y; 1357 z = -z; 1358 break; 1359 case SensorManager.SENSOR_MAGNETIC_FIELD: 1360 x = -x; 1361 y = -y; 1362 break; 1363 } 1364 values[0] = x; 1365 values[1] = y; 1366 values[2] = z; 1367 values[3] = x; 1368 values[4] = y; 1369 values[5] = z; 1370 // TODO: add support for 180 and 270 orientations 1371 if (orientation == Surface.ROTATION_90) { 1372 switch (sensor) { 1373 case SENSOR_ACCELEROMETER: 1374 case SENSOR_MAGNETIC_FIELD: 1375 values[0] =-y; 1376 values[1] = x; 1377 values[2] = z; 1378 break; 1379 case SENSOR_ORIENTATION: 1380 case SENSOR_ORIENTATION_RAW: 1381 values[0] = x + ((x < 270) ? 90 : -270); 1382 values[1] = z; 1383 values[2] = y; 1384 break; 1385 } 1386 } 1387 } 1388 } 1389 1390 class LmsFilter { 1391 private static final int SENSORS_RATE_MS = 20; 1392 private static final int COUNT = 12; 1393 private static final float PREDICTION_RATIO = 1.0f/3.0f; 1394 private static final float PREDICTION_TIME = (SENSORS_RATE_MS*COUNT/1000.0f)*PREDICTION_RATIO; 1395 private float mV[] = new float[COUNT*2]; 1396 private float mT[] = new float[COUNT*2]; 1397 private int mIndex; 1398 1399 public LmsFilter() { 1400 mIndex = COUNT; 1401 } 1402 1403 public float filter(long time, float in) { 1404 float v = in; 1405 final float ns = 1.0f / 1000000000.0f; 1406 final float t = time*ns; 1407 float v1 = mV[mIndex]; 1408 if ((v-v1) > 180) { 1409 v -= 360; 1410 } else if ((v1-v) > 180) { 1411 v += 360; 1412 } 1413 /* Manage the circular buffer, we write the data twice spaced 1414 * by COUNT values, so that we don't have to copy the array 1415 * when it's full 1416 */ 1417 mIndex++; 1418 if (mIndex >= COUNT*2) 1419 mIndex = COUNT; 1420 mV[mIndex] = v; 1421 mT[mIndex] = t; 1422 mV[mIndex-COUNT] = v; 1423 mT[mIndex-COUNT] = t; 1424 1425 float A, B, C, D, E; 1426 float a, b; 1427 int i; 1428 1429 A = B = C = D = E = 0; 1430 for (i=0 ; i<COUNT-1 ; i++) { 1431 final int j = mIndex - 1 - i; 1432 final float Z = mV[j]; 1433 final float T = 0.5f*(mT[j] + mT[j+1]) - t; 1434 float dT = mT[j] - mT[j+1]; 1435 dT *= dT; 1436 A += Z*dT; 1437 B += T*(T*dT); 1438 C += (T*dT); 1439 D += Z*(T*dT); 1440 E += dT; 1441 } 1442 b = (A*B + C*D) / (E*B + C*C); 1443 a = (E*b - A) / C; 1444 float f = b + PREDICTION_TIME*a; 1445 1446 // Normalize 1447 f *= (1.0f / 360.0f); 1448 if (((f>=0)?f:-f) >= 0.5f) 1449 f = f - (float)Math.ceil(f + 0.5f) + 1.0f; 1450 if (f < 0) 1451 f += 1.0f; 1452 f *= 360.0f; 1453 return f; 1454 } 1455 } 1456 1457 1458 private static native void nativeClassInit(); 1459 1460 private static native int sensors_module_init(); 1461 private static native int sensors_module_get_next_sensor(Sensor sensor, int next); 1462 1463 // Used within this module from outside SensorManager, don't make private 1464 static native int sensors_data_init(); 1465 static native int sensors_data_uninit(); 1466 static native int sensors_data_open(FileDescriptor fd); 1467 static native int sensors_data_close(); 1468 static native int sensors_data_poll(float[] values, int[] status, long[] timestamp); 1469} 1470