SensorManager.java revision d24b8183b93e781080b2c16c487e60d51c12da31
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 return; 308 } 309 // this thread is guaranteed to be unique 310 sensors_data_open(mSensorDataFd.getFileDescriptor()); 311 try { 312 mSensorDataFd.close(); 313 } catch (IOException e) { 314 // *shrug* 315 Log.e(TAG, "IOException: ", e); 316 } 317 mSensorDataFd = null; 318 319 320 while (true) { 321 // wait for an event 322 final int sensor = sensors_data_poll(values, status, timestamp); 323 324 if (sensor == -1) { 325 // we lost the connection to the event stream. this happens 326 // when the last listener is removed. 327 Log.d(TAG, "_sensors_data_poll() failed, we bail out."); 328 break; 329 } 330 331 int accuracy = status[0]; 332 synchronized (sListeners) { 333 if (sListeners.isEmpty()) { 334 // we have no more listeners, terminate the thread 335 sensors_data_close(); 336 mThread = null; 337 break; 338 } 339 final Sensor sensorObject = sHandleToSensor.get(sensor); 340 if (sensorObject != null) { 341 // report the sensor event to all listeners that 342 // care about it. 343 final int size = sListeners.size(); 344 for (int i=0 ; i<size ; i++) { 345 ListenerDelegate listener = sListeners.get(i); 346 if (listener.hasSensor(sensorObject)) { 347 // this is asynchronous (okay to call 348 // with sListeners lock held). 349 listener.onSensorChangedLocked(sensorObject, 350 values, timestamp, accuracy); 351 } 352 } 353 } 354 } 355 } 356 //Log.d(TAG, "exiting main sensor thread"); 357 } 358 } 359 } 360 361 /*-----------------------------------------------------------------------*/ 362 363 private class ListenerDelegate extends Binder { 364 final SensorEventListener mSensorEventListener; 365 private final ArrayList<Sensor> mSensorList = new ArrayList<Sensor>(); 366 private final Handler mHandler; 367 private SensorEvent mValuesPool; 368 public int mSensors; 369 370 ListenerDelegate(SensorEventListener listener, Sensor sensor, Handler handler) { 371 mSensorEventListener = listener; 372 Looper looper = (handler != null) ? handler.getLooper() : mMainLooper; 373 // currently we create one Handler instance per listener, but we could 374 // have one per looper (we'd need to pass the ListenerDelegate 375 // instance to handleMessage and keep track of them separately). 376 mHandler = new Handler(looper) { 377 @Override 378 public void handleMessage(Message msg) { 379 SensorEvent t = (SensorEvent)msg.obj; 380 if (t.accuracy >= 0) { 381 mSensorEventListener.onAccuracyChanged(t.sensor, t.accuracy); 382 } 383 mSensorEventListener.onSensorChanged(t); 384 returnToPool(t); 385 } 386 }; 387 addSensor(sensor); 388 } 389 390 protected SensorEvent createSensorEvent() { 391 // maximal size for all legacy events is 3 392 return new SensorEvent(3); 393 } 394 395 protected SensorEvent getFromPool() { 396 SensorEvent t = null; 397 synchronized (this) { 398 // remove the array from the pool 399 t = mValuesPool; 400 mValuesPool = null; 401 } 402 if (t == null) { 403 // the pool was empty, we need a new one 404 t = createSensorEvent(); 405 } 406 return t; 407 } 408 409 protected void returnToPool(SensorEvent t) { 410 synchronized (this) { 411 // put back the array into the pool 412 if (mValuesPool == null) { 413 mValuesPool = t; 414 } 415 } 416 } 417 418 Object getListener() { 419 return mSensorEventListener; 420 } 421 422 int addSensor(Sensor sensor) { 423 mSensors |= 1<<sensor.getHandle(); 424 mSensorList.add(sensor); 425 return mSensors; 426 } 427 int removeSensor(Sensor sensor) { 428 mSensors &= ~(1<<sensor.getHandle()); 429 mSensorList.remove(sensor); 430 return mSensors; 431 } 432 boolean hasSensor(Sensor sensor) { 433 return ((mSensors & (1<<sensor.getHandle())) != 0); 434 } 435 List<Sensor> getSensors() { 436 return mSensorList; 437 } 438 439 void onSensorChangedLocked(Sensor sensor, float[] values, long[] timestamp, int accuracy) { 440 SensorEvent t = getFromPool(); 441 final float[] v = t.values; 442 v[0] = values[0]; 443 v[1] = values[1]; 444 v[2] = values[2]; 445 t.timestamp = timestamp[0]; 446 t.accuracy = accuracy; 447 t.sensor = sensor; 448 Message msg = Message.obtain(); 449 msg.what = 0; 450 msg.obj = t; 451 mHandler.sendMessage(msg); 452 } 453 } 454 455 /** 456 * {@hide} 457 */ 458 public SensorManager(Looper mainLooper) { 459 mSensorService = ISensorService.Stub.asInterface( 460 ServiceManager.getService(Context.SENSOR_SERVICE)); 461 mMainLooper = mainLooper; 462 463 464 synchronized(sListeners) { 465 if (!sSensorModuleInitialized) { 466 sSensorModuleInitialized = true; 467 468 nativeClassInit(); 469 470 sWindowManager = IWindowManager.Stub.asInterface( 471 ServiceManager.getService("window")); 472 if (sWindowManager != null) { 473 // if it's null we're running in the system process 474 // which won't get the rotated values 475 try { 476 sRotation = sWindowManager.watchRotation(this); 477 } catch (RemoteException e) { 478 } 479 } 480 481 // initialize the sensor list 482 sensors_module_init(); 483 final ArrayList<Sensor> fullList = sFullSensorsList; 484 int i = 0; 485 do { 486 Sensor sensor = new Sensor(); 487 i = sensors_module_get_next_sensor(sensor, i); 488 489 if (i>=0) { 490 Log.d(TAG, "found sensor: " + sensor.getName() + 491 ", handle=" + sensor.getHandle()); 492 sensor.setLegacyType(getLegacySensorType(sensor.getType())); 493 fullList.add(sensor); 494 sHandleToSensor.append(sensor.getHandle(), sensor); 495 } 496 } while (i>0); 497 498 sSensorThread = new SensorThread(); 499 } 500 } 501 } 502 503 private int getLegacySensorType(int type) { 504 switch (type) { 505 case Sensor.TYPE_ACCELEROMETER: 506 return SENSOR_ACCELEROMETER; 507 case Sensor.TYPE_MAGNETIC_FIELD: 508 return SENSOR_MAGNETIC_FIELD; 509 case Sensor.TYPE_ORIENTATION: 510 return SENSOR_ORIENTATION_RAW; 511 case Sensor.TYPE_TEMPERATURE: 512 return SENSOR_TEMPERATURE; 513 } 514 return 0; 515 } 516 517 /** @return available sensors. 518 * @deprecated This method is deprecated, use 519 * {@link SensorManager#getSensorList(int)} instead 520 */ 521 @Deprecated 522 public int getSensors() { 523 int result = 0; 524 final ArrayList<Sensor> fullList = sFullSensorsList; 525 for (Sensor i : fullList) { 526 switch (i.getType()) { 527 case Sensor.TYPE_ACCELEROMETER: 528 result |= SensorManager.SENSOR_ACCELEROMETER; 529 break; 530 case Sensor.TYPE_MAGNETIC_FIELD: 531 result |= SensorManager.SENSOR_MAGNETIC_FIELD; 532 break; 533 case Sensor.TYPE_ORIENTATION: 534 result |= SensorManager.SENSOR_ORIENTATION | 535 SensorManager.SENSOR_ORIENTATION_RAW; 536 break; 537 } 538 } 539 return result; 540 } 541 542 /** 543 * Use this method to get the list of available sensors of a certain 544 * type. Make multiple calls to get sensors of different types or use 545 * {@link android.hardware.Sensor#TYPE_ALL Sensor.TYPE_ALL} to get all 546 * the sensors. 547 * 548 * @param type of sensors requested 549 * @return a list of sensors matching the asked type. 550 */ 551 public List<Sensor> getSensorList(int type) { 552 // cache the returned lists the first time 553 List<Sensor> list; 554 final ArrayList<Sensor> fullList = sFullSensorsList; 555 synchronized(fullList) { 556 list = sSensorListByType.get(type); 557 if (list == null) { 558 if (type == Sensor.TYPE_ALL) { 559 list = fullList; 560 } else { 561 list = new ArrayList<Sensor>(); 562 for (Sensor i : fullList) { 563 if (i.getType() == type) 564 list.add(i); 565 } 566 } 567 list = Collections.unmodifiableList(list); 568 sSensorListByType.append(type, list); 569 } 570 } 571 return list; 572 } 573 574 /** 575 * Use this method to get the default sensor for a given type. Note that 576 * the returned sensor could be a composite sensor, and its data could be 577 * averaged or filtered. If you need to access the raw sensors use 578 * {@link SensorManager#getSensorList(int) getSensorList}. 579 * 580 * 581 * @param type of sensors requested 582 * @return the default sensors matching the asked type. 583 */ 584 public Sensor getDefaultSensor(int type) { 585 // TODO: need to be smarter, for now, just return the 1st sensor 586 List<Sensor> l = getSensorList(type); 587 return l.isEmpty() ? null : l.get(0); 588 } 589 590 591 /** 592 * Registers a listener for given sensors. 593 * @deprecated This method is deprecated, use 594 * {@link SensorManager#registerListener(SensorEventListener, Sensor, int)} 595 * instead. 596 * 597 * @param listener sensor listener object 598 * @param sensors a bit masks of the sensors to register to 599 * 600 * @return true if the sensor is supported and successfully enabled 601 */ 602 @Deprecated 603 public boolean registerListener(SensorListener listener, int sensors) { 604 return registerListener(listener, sensors, SENSOR_DELAY_NORMAL); 605 } 606 607 /** 608 * Registers a SensorListener for given sensors. 609 * @deprecated This method is deprecated, use 610 * {@link SensorManager#registerListener(SensorEventListener, Sensor, int)} 611 * instead. 612 * 613 * @param listener sensor listener object 614 * @param sensors a bit masks of the sensors to register to 615 * @param rate rate of events. This is only a hint to the system. events 616 * may be received faster or slower than the specified rate. Usually events 617 * are received faster. 618 * 619 * @return true if the sensor is supported and successfully enabled 620 */ 621 @Deprecated 622 public boolean registerListener(SensorListener listener, int sensors, int rate) { 623 boolean result = false; 624 result = registerLegacyListener(SENSOR_ACCELEROMETER, Sensor.TYPE_ACCELEROMETER, 625 listener, sensors, rate) || result; 626 result = registerLegacyListener(SENSOR_MAGNETIC_FIELD, Sensor.TYPE_MAGNETIC_FIELD, 627 listener, sensors, rate) || result; 628 result = registerLegacyListener(SENSOR_ORIENTATION_RAW, Sensor.TYPE_ORIENTATION, 629 listener, sensors, rate) || result; 630 result = registerLegacyListener(SENSOR_ORIENTATION, Sensor.TYPE_ORIENTATION, 631 listener, sensors, rate) || result; 632 result = registerLegacyListener(SENSOR_TEMPERATURE, Sensor.TYPE_TEMPERATURE, 633 listener, sensors, rate) || result; 634 return result; 635 } 636 637 @SuppressWarnings("deprecation") 638 private boolean registerLegacyListener(int legacyType, int type, 639 SensorListener listener, int sensors, int rate) 640 { 641 boolean result = false; 642 // Are we activating this legacy sensor? 643 if ((sensors & legacyType) != 0) { 644 // if so, find a suitable Sensor 645 Sensor sensor = getDefaultSensor(type); 646 if (sensor != null) { 647 // If we don't already have one, create a LegacyListener 648 // to wrap this listener and process the events as 649 // they are expected by legacy apps. 650 LegacyListener legacyListener = null; 651 synchronized (mLegacyListenersMap) { 652 legacyListener = mLegacyListenersMap.get(listener); 653 if (legacyListener == null) { 654 // we didn't find a LegacyListener for this client, 655 // create one, and put it in our list. 656 legacyListener = new LegacyListener(listener); 657 mLegacyListenersMap.put(listener, legacyListener); 658 } 659 } 660 // register this legacy sensor with this legacy listener 661 legacyListener.registerSensor(legacyType); 662 // and finally, register the legacy listener with the new apis 663 result = registerListener(legacyListener, sensor, rate); 664 } 665 } 666 return result; 667 } 668 669 /** 670 * Unregisters a listener for the sensors with which it is registered. 671 * @deprecated This method is deprecated, use 672 * {@link SensorManager#unregisterListener(SensorEventListener, Sensor)} 673 * instead. 674 * 675 * @param listener a SensorListener object 676 * @param sensors a bit masks of the sensors to unregister from 677 */ 678 @Deprecated 679 public void unregisterListener(SensorListener listener, int sensors) { 680 unregisterLegacyListener(SENSOR_ACCELEROMETER, Sensor.TYPE_ACCELEROMETER, 681 listener, sensors); 682 unregisterLegacyListener(SENSOR_MAGNETIC_FIELD, Sensor.TYPE_MAGNETIC_FIELD, 683 listener, sensors); 684 unregisterLegacyListener(SENSOR_ORIENTATION_RAW, Sensor.TYPE_ORIENTATION, 685 listener, sensors); 686 unregisterLegacyListener(SENSOR_ORIENTATION, Sensor.TYPE_ORIENTATION, 687 listener, sensors); 688 unregisterLegacyListener(SENSOR_TEMPERATURE, Sensor.TYPE_TEMPERATURE, 689 listener, sensors); 690 } 691 692 @SuppressWarnings("deprecation") 693 private void unregisterLegacyListener(int legacyType, int type, 694 SensorListener listener, int sensors) 695 { 696 // do we know about this listener? 697 LegacyListener legacyListener = null; 698 synchronized (mLegacyListenersMap) { 699 legacyListener = mLegacyListenersMap.get(listener); 700 } 701 if (legacyListener != null) { 702 // Are we deactivating this legacy sensor? 703 if ((sensors & legacyType) != 0) { 704 // if so, find the corresponding Sensor 705 Sensor sensor = getDefaultSensor(type); 706 if (sensor != null) { 707 // unregister this legacy sensor and if we don't 708 // need the corresponding Sensor, unregister it too 709 if (legacyListener.unregisterSensor(legacyType)) { 710 // corresponding sensor not needed, unregister 711 unregisterListener(legacyListener, sensor); 712 // finally check if we still need the legacyListener 713 // in our mapping, if not, get rid of it too. 714 synchronized(sListeners) { 715 boolean found = false; 716 for (ListenerDelegate i : sListeners) { 717 if (i.getListener() == legacyListener) { 718 found = true; 719 break; 720 } 721 } 722 if (!found) { 723 synchronized (mLegacyListenersMap) { 724 mLegacyListenersMap.remove(listener); 725 } 726 } 727 } 728 } 729 } 730 } 731 } 732 } 733 734 /** 735 * Unregisters a listener for all sensors. 736 * @deprecated This method is deprecated, use 737 * {@link SensorManager#unregisterListener(SensorEventListener)} 738 * instead. 739 * 740 * @param listener a SensorListener object 741 */ 742 @Deprecated 743 public void unregisterListener(SensorListener listener) { 744 unregisterListener(listener, SENSOR_ALL | SENSOR_ORIENTATION_RAW); 745 } 746 747 /** 748 * Unregisters a listener for the sensors with which it is registered. 749 * 750 * @param listener a SensorEventListener object 751 * @param sensor the sensor to unregister from 752 * 753 */ 754 public void unregisterListener(SensorEventListener listener, Sensor sensor) { 755 unregisterListener((Object)listener, sensor); 756 } 757 758 /** 759 * Unregisters a listener for all sensors. 760 * 761 * @param listener a SensorListener object 762 * 763 */ 764 public void unregisterListener(SensorEventListener listener) { 765 unregisterListener((Object)listener); 766 } 767 768 769 /** 770 * Registers a {@link android.hardware.SensorEventListener SensorEventListener} 771 * for the given sensor. 772 * 773 * @param listener A {@link android.hardware.SensorEventListener SensorEventListener} object. 774 * @param sensor The {@link android.hardware.Sensor Sensor} to register to. 775 * @param rate The rate {@link android.hardware.SensorEvent sensor events} are delivered at. 776 * This is only a hint to the system. Events may be received faster or 777 * slower than the specified rate. Usually events are received faster. 778 * 779 * @return true if the sensor is supported and successfully enabled. 780 * 781 */ 782 public boolean registerListener(SensorEventListener listener, Sensor sensor, int rate) { 783 return registerListener(listener, sensor, rate, null); 784 } 785 786 /** 787 * Registers a {@link android.hardware.SensorEventListener SensorEventListener} 788 * for the given sensor. 789 * 790 * @param listener A {@link android.hardware.SensorEventListener SensorEventListener} object. 791 * @param sensor The {@link android.hardware.Sensor Sensor} to register to. 792 * @param rate The rate {@link android.hardware.SensorEvent sensor events} are delivered at. 793 * This is only a hint to the system. Events may be received faster or 794 * slower than the specified rate. Usually events are received faster. 795 * @param handler The {@link android.os.Handler Handler} the 796 * {@link android.hardware.SensorEvent sensor events} will be delivered to. 797 * 798 * @return true if the sensor is supported and successfully enabled. 799 * 800 */ 801 public boolean registerListener(SensorEventListener listener, Sensor sensor, int rate, 802 Handler handler) { 803 boolean result; 804 int delay = -1; 805 switch (rate) { 806 case SENSOR_DELAY_FASTEST: 807 delay = 0; 808 break; 809 case SENSOR_DELAY_GAME: 810 delay = 20; 811 break; 812 case SENSOR_DELAY_UI: 813 delay = 60; 814 break; 815 case SENSOR_DELAY_NORMAL: 816 delay = 200; 817 break; 818 default: 819 return false; 820 } 821 822 try { 823 synchronized (sListeners) { 824 ListenerDelegate l = null; 825 for (ListenerDelegate i : sListeners) { 826 if (i.getListener() == listener) { 827 l = i; 828 break; 829 } 830 } 831 832 String name = sensor.getName(); 833 int handle = sensor.getHandle(); 834 if (l == null) { 835 l = new ListenerDelegate(listener, sensor, handler); 836 result = mSensorService.enableSensor(l, name, handle, delay); 837 if (result) { 838 sListeners.add(l); 839 sListeners.notify(); 840 } 841 if (!sListeners.isEmpty()) { 842 sSensorThread.startLocked(mSensorService); 843 } 844 } else { 845 result = mSensorService.enableSensor(l, name, handle, delay); 846 if (result) { 847 l.addSensor(sensor); 848 } 849 } 850 } 851 } catch (RemoteException e) { 852 Log.e(TAG, "RemoteException in registerListener: ", e); 853 result = false; 854 } 855 return result; 856 } 857 858 private void unregisterListener(Object listener, Sensor sensor) { 859 try { 860 synchronized (sListeners) { 861 final int size = sListeners.size(); 862 for (int i=0 ; i<size ; i++) { 863 ListenerDelegate l = sListeners.get(i); 864 if (l.getListener() == listener) { 865 // disable these sensors 866 String name = sensor.getName(); 867 int handle = sensor.getHandle(); 868 mSensorService.enableSensor(l, name, handle, SENSOR_DISABLE); 869 // if we have no more sensors enabled on this listener, 870 // take it off the list. 871 if (l.removeSensor(sensor) == 0) { 872 sListeners.remove(i); 873 } 874 break; 875 } 876 } 877 } 878 } catch (RemoteException e) { 879 Log.e(TAG, "RemoteException in unregisterListener: ", e); 880 } 881 } 882 883 private void unregisterListener(Object listener) { 884 try { 885 synchronized (sListeners) { 886 final int size = sListeners.size(); 887 for (int i=0 ; i<size ; i++) { 888 ListenerDelegate l = sListeners.get(i); 889 if (l.getListener() == listener) { 890 // disable all sensors for this listener 891 for (Sensor sensor : l.getSensors()) { 892 String name = sensor.getName(); 893 int handle = sensor.getHandle(); 894 mSensorService.enableSensor(l, name, handle, SENSOR_DISABLE); 895 } 896 sListeners.remove(i); 897 break; 898 } 899 } 900 } 901 } catch (RemoteException e) { 902 Log.e(TAG, "RemoteException in unregisterListener: ", e); 903 } 904 } 905 906 /** 907 * Computes the inclination matrix <b>I</b> as well as the rotation 908 * matrix <b>R</b> transforming a vector from the 909 * device coordinate system to the world's coordinate system which is 910 * defined as a direct orthonormal basis, where: 911 * 912 * <li>X is defined as the vector product <b>Y.Z</b> (It is tangential to 913 * the ground at the device's current location and roughly points East).</li> 914 * <li>Y is tangential to the ground at the device's current location and 915 * points towards the magnetic North Pole.</li> 916 * <li>Z points towards the sky and is perpendicular to the ground.</li> 917 * <p> 918 * <hr> 919 * <p>By definition: 920 * <p>[0 0 g] = <b>R</b> * <b>gravity</b> (g = magnitude of gravity) 921 * <p>[0 m 0] = <b>I</b> * <b>R</b> * <b>geomagnetic</b> 922 * (m = magnitude of geomagnetic field) 923 * <p><b>R</b> is the identity matrix when the device is aligned with the 924 * world's coordinate system, that is, when the device's X axis points 925 * toward East, the Y axis points to the North Pole and the device is facing 926 * the sky. 927 * 928 * <p><b>I</b> is a rotation matrix transforming the geomagnetic 929 * vector into the same coordinate space as gravity (the world's coordinate 930 * space). <b>I</b> is a simple rotation around the X axis. 931 * The inclination angle in radians can be computed with 932 * {@link #getInclination}. 933 * <hr> 934 * 935 * <p> Each matrix is returned either as a 3x3 or 4x4 row-major matrix 936 * depending on the length of the passed array: 937 * <p><u>If the array length is 16:</u> 938 * <pre> 939 * / M[ 0] M[ 1] M[ 2] M[ 3] \ 940 * | M[ 4] M[ 5] M[ 6] M[ 7] | 941 * | M[ 8] M[ 9] M[10] M[11] | 942 * \ M[12] M[13] M[14] M[15] / 943 *</pre> 944 * This matrix is ready to be used by OpenGL ES's 945 * {@link javax.microedition.khronos.opengles.GL10#glLoadMatrixf(float[], int) 946 * glLoadMatrixf(float[], int)}. 947 * <p>Note that because OpenGL matrices are column-major matrices you must 948 * transpose the matrix before using it. However, since the matrix is a 949 * rotation matrix, its transpose is also its inverse, conveniently, it is 950 * often the inverse of the rotation that is needed for rendering; it can 951 * therefore be used with OpenGL ES directly. 952 * <p> 953 * Also note that the returned matrices always have this form: 954 * <pre> 955 * / M[ 0] M[ 1] M[ 2] 0 \ 956 * | M[ 4] M[ 5] M[ 6] 0 | 957 * | M[ 8] M[ 9] M[10] 0 | 958 * \ 0 0 0 1 / 959 *</pre> 960 * <p><u>If the array length is 9:</u> 961 * <pre> 962 * / M[ 0] M[ 1] M[ 2] \ 963 * | M[ 3] M[ 4] M[ 5] | 964 * \ M[ 6] M[ 7] M[ 8] / 965 *</pre> 966 * 967 * <hr> 968 * <p>The inverse of each matrix can be computed easily by taking its 969 * transpose. 970 * 971 * <p>The matrices returned by this function are meaningful only when the 972 * device is not free-falling and it is not close to the magnetic north. 973 * If the device is accelerating, or placed into a strong magnetic field, 974 * the returned matrices may be inaccurate. 975 * 976 * @param R is an array of 9 floats holding the rotation matrix <b>R</b> 977 * when this function returns. R can be null.<p> 978 * @param I is an array of 9 floats holding the rotation matrix <b>I</b> 979 * when this function returns. I can be null.<p> 980 * @param gravity is an array of 3 floats containing the gravity vector 981 * expressed in the device's coordinate. You can simply use the 982 * {@link android.hardware.SensorEvent#values values} 983 * returned by a {@link android.hardware.SensorEvent SensorEvent} of a 984 * {@link android.hardware.Sensor Sensor} of type 985 * {@link android.hardware.Sensor#TYPE_ACCELEROMETER TYPE_ACCELEROMETER}.<p> 986 * @param geomagnetic is an array of 3 floats containing the geomagnetic 987 * vector expressed in the device's coordinate. You can simply use the 988 * {@link android.hardware.SensorEvent#values values} 989 * returned by a {@link android.hardware.SensorEvent SensorEvent} of a 990 * {@link android.hardware.Sensor Sensor} of type 991 * {@link android.hardware.Sensor#TYPE_MAGNETIC_FIELD TYPE_MAGNETIC_FIELD}. 992 * @return 993 * true on success<p> 994 * false on failure (for instance, if the device is in free fall). 995 * On failure the output matrices are not modified. 996 */ 997 998 public static boolean getRotationMatrix(float[] R, float[] I, 999 float[] gravity, float[] geomagnetic) { 1000 // TODO: move this to native code for efficiency 1001 float Ax = gravity[0]; 1002 float Ay = gravity[1]; 1003 float Az = gravity[2]; 1004 final float Ex = geomagnetic[0]; 1005 final float Ey = geomagnetic[1]; 1006 final float Ez = geomagnetic[2]; 1007 float Hx = Ey*Az - Ez*Ay; 1008 float Hy = Ez*Ax - Ex*Az; 1009 float Hz = Ex*Ay - Ey*Ax; 1010 final float normH = (float)Math.sqrt(Hx*Hx + Hy*Hy + Hz*Hz); 1011 if (normH < 0.1f) { 1012 // device is close to free fall (or in space?), or close to 1013 // magnetic north pole. Typical values are > 100. 1014 return false; 1015 } 1016 final float invH = 1.0f / normH; 1017 Hx *= invH; 1018 Hy *= invH; 1019 Hz *= invH; 1020 final float invA = 1.0f / (float)Math.sqrt(Ax*Ax + Ay*Ay + Az*Az); 1021 Ax *= invA; 1022 Ay *= invA; 1023 Az *= invA; 1024 final float Mx = Ay*Hz - Az*Hy; 1025 final float My = Az*Hx - Ax*Hz; 1026 final float Mz = Ax*Hy - Ay*Hx; 1027 if (R != null) { 1028 if (R.length == 9) { 1029 R[0] = Hx; R[1] = Hy; R[2] = Hz; 1030 R[3] = Mx; R[4] = My; R[5] = Mz; 1031 R[6] = Ax; R[7] = Ay; R[8] = Az; 1032 } else if (R.length == 16) { 1033 R[0] = Hx; R[1] = Hy; R[2] = Hz; R[3] = 0; 1034 R[4] = Mx; R[5] = My; R[6] = Mz; R[7] = 0; 1035 R[8] = Ax; R[9] = Ay; R[10] = Az; R[11] = 0; 1036 R[12] = 0; R[13] = 0; R[14] = 0; R[15] = 1; 1037 } 1038 } 1039 if (I != null) { 1040 // compute the inclination matrix by projecting the geomagnetic 1041 // vector onto the Z (gravity) and X (horizontal component 1042 // of geomagnetic vector) axes. 1043 final float invE = 1.0f / (float)Math.sqrt(Ex*Ex + Ey*Ey + Ez*Ez); 1044 final float c = (Ex*Mx + Ey*My + Ez*Mz) * invE; 1045 final float s = (Ex*Ax + Ey*Ay + Ez*Az) * invE; 1046 if (I.length == 9) { 1047 I[0] = 1; I[1] = 0; I[2] = 0; 1048 I[3] = 0; I[4] = c; I[5] = s; 1049 I[6] = 0; I[7] =-s; I[8] = c; 1050 } else if (I.length == 16) { 1051 I[0] = 1; I[1] = 0; I[2] = 0; 1052 I[4] = 0; I[5] = c; I[6] = s; 1053 I[8] = 0; I[9] =-s; I[10]= c; 1054 I[3] = I[7] = I[11] = I[12] = I[13] = I[14] = 0; 1055 I[15] = 1; 1056 } 1057 } 1058 return true; 1059 } 1060 1061 /** 1062 * Computes the geomagnetic inclination angle in radians from the 1063 * inclination matrix <b>I</b> returned by {@link #getRotationMatrix}. 1064 * @param I inclination matrix see {@link #getRotationMatrix}. 1065 * @return The geomagnetic inclination angle in radians. 1066 */ 1067 public static float getInclination(float[] I) { 1068 if (I.length == 9) { 1069 return (float)Math.atan2(I[5], I[4]); 1070 } else { 1071 return (float)Math.atan2(I[6], I[5]); 1072 } 1073 } 1074 1075 /** 1076 * Rotates the supplied rotation matrix so it is expressed in a 1077 * different coordinate system. This is typically used when an application 1078 * needs to compute the three orientation angles of the device (see 1079 * {@link #getOrientation}) in a different coordinate system. 1080 * 1081 * <p>When the rotation matrix is used for drawing (for instance with 1082 * OpenGL ES), it usually <b>doesn't need</b> to be transformed by this 1083 * function, unless the screen is physically rotated, such as when used 1084 * in landscape mode. 1085 * 1086 * <p><u>Examples:</u><p> 1087 * 1088 * <li>Using the camera (Y axis along the camera's axis) for an augmented 1089 * reality application where the rotation angles are needed :</li><p> 1090 * 1091 * <code>remapCoordinateSystem(inR, AXIS_X, AXIS_Z, outR);</code><p> 1092 * 1093 * <li>Using the device as a mechanical compass in landscape mode:</li><p> 1094 * 1095 * <code>remapCoordinateSystem(inR, AXIS_Y, AXIS_MINUS_X, outR);</code><p> 1096 * 1097 * Beware of the above example. This call is needed only if the device is 1098 * physically used in landscape mode to calculate the rotation angles (see 1099 * {@link #getOrientation}). 1100 * If the rotation matrix is also used for rendering, it may not need to 1101 * be transformed, for instance if your {@link android.app.Activity 1102 * Activity} is running in landscape mode. 1103 * 1104 * <p>Since the resulting coordinate system is orthonormal, only two axes 1105 * need to be specified. 1106 * 1107 * @param inR the rotation matrix to be transformed. Usually it is the 1108 * matrix returned by {@link #getRotationMatrix}. 1109 * @param X defines on which world axis and direction the X axis of the 1110 * device is mapped. 1111 * @param Y defines on which world axis and direction the Y axis of the 1112 * device is mapped. 1113 * @param outR the transformed rotation matrix. inR and outR can be the same 1114 * array, but it is not recommended for performance reason. 1115 * @return true on success. false if the input parameters are incorrect, for 1116 * instance if X and Y define the same axis. Or if inR and outR don't have 1117 * the same length. 1118 */ 1119 1120 public static boolean remapCoordinateSystem(float[] inR, int X, int Y, 1121 float[] outR) 1122 { 1123 if (inR == outR) { 1124 final float[] temp = mTempMatrix; 1125 synchronized(temp) { 1126 // we don't expect to have a lot of contention 1127 if (remapCoordinateSystemImpl(inR, X, Y, temp)) { 1128 final int size = outR.length; 1129 for (int i=0 ; i<size ; i++) 1130 outR[i] = temp[i]; 1131 return true; 1132 } 1133 } 1134 } 1135 return remapCoordinateSystemImpl(inR, X, Y, outR); 1136 } 1137 1138 private static boolean remapCoordinateSystemImpl(float[] inR, int X, int Y, 1139 float[] outR) 1140 { 1141 /* 1142 * X and Y define a rotation matrix 'r': 1143 * 1144 * (X==1)?((X&0x80)?-1:1):0 (X==2)?((X&0x80)?-1:1):0 (X==3)?((X&0x80)?-1:1):0 1145 * (Y==1)?((Y&0x80)?-1:1):0 (Y==2)?((Y&0x80)?-1:1):0 (Y==3)?((X&0x80)?-1:1):0 1146 * r[0] ^ r[1] 1147 * 1148 * where the 3rd line is the vector product of the first 2 lines 1149 * 1150 */ 1151 1152 final int length = outR.length; 1153 if (inR.length != length) 1154 return false; // invalid parameter 1155 if ((X & 0x7C)!=0 || (Y & 0x7C)!=0) 1156 return false; // invalid parameter 1157 if (((X & 0x3)==0) || ((Y & 0x3)==0)) 1158 return false; // no axis specified 1159 if ((X & 0x3) == (Y & 0x3)) 1160 return false; // same axis specified 1161 1162 // Z is "the other" axis, its sign is either +/- sign(X)*sign(Y) 1163 // this can be calculated by exclusive-or'ing X and Y; except for 1164 // the sign inversion (+/-) which is calculated below. 1165 int Z = X ^ Y; 1166 1167 // extract the axis (remove the sign), offset in the range 0 to 2. 1168 final int x = (X & 0x3)-1; 1169 final int y = (Y & 0x3)-1; 1170 final int z = (Z & 0x3)-1; 1171 1172 // compute the sign of Z (whether it needs to be inverted) 1173 final int axis_y = (z+1)%3; 1174 final int axis_z = (z+2)%3; 1175 if (((x^axis_y)|(y^axis_z)) != 0) 1176 Z ^= 0x80; 1177 1178 final boolean sx = (X>=0x80); 1179 final boolean sy = (Y>=0x80); 1180 final boolean sz = (Z>=0x80); 1181 1182 // Perform R * r, in avoiding actual muls and adds. 1183 final int rowLength = ((length==16)?4:3); 1184 for (int j=0 ; j<3 ; j++) { 1185 final int offset = j*rowLength; 1186 for (int i=0 ; i<3 ; i++) { 1187 if (x==i) outR[offset+i] = sx ? -inR[offset+0] : inR[offset+0]; 1188 if (y==i) outR[offset+i] = sy ? -inR[offset+1] : inR[offset+1]; 1189 if (z==i) outR[offset+i] = sz ? -inR[offset+2] : inR[offset+2]; 1190 } 1191 } 1192 if (length == 16) { 1193 outR[3] = outR[7] = outR[11] = outR[12] = outR[13] = outR[14] = 0; 1194 outR[15] = 1; 1195 } 1196 return true; 1197 } 1198 1199 /** 1200 * Computes the device's orientation based on the rotation matrix. 1201 * <p> When it returns, the array values is filled with the result: 1202 * <li>values[0]: <i>azimuth</i>, rotation around the Z axis.</li> 1203 * <li>values[1]: <i>pitch</i>, rotation around the X axis.</li> 1204 * <li>values[2]: <i>roll</i>, rotation around the Y axis.</li> 1205 * <p> 1206 * 1207 * @param R rotation matrix see {@link #getRotationMatrix}. 1208 * @param values an array of 3 floats to hold the result. 1209 * @return The array values passed as argument. 1210 */ 1211 public static float[] getOrientation(float[] R, float values[]) { 1212 /* 1213 * 4x4 (length=16) case: 1214 * / R[ 0] R[ 1] R[ 2] 0 \ 1215 * | R[ 4] R[ 5] R[ 6] 0 | 1216 * | R[ 8] R[ 9] R[10] 0 | 1217 * \ 0 0 0 1 / 1218 * 1219 * 3x3 (length=9) case: 1220 * / R[ 0] R[ 1] R[ 2] \ 1221 * | R[ 3] R[ 4] R[ 5] | 1222 * \ R[ 6] R[ 7] R[ 8] / 1223 * 1224 */ 1225 if (R.length == 9) { 1226 values[0] = (float)Math.atan2(R[1], R[4]); 1227 values[1] = (float)Math.asin(-R[7]); 1228 values[2] = (float)Math.atan2(-R[6], R[8]); 1229 } else { 1230 values[0] = (float)Math.atan2(R[1], R[5]); 1231 values[1] = (float)Math.asin(-R[9]); 1232 values[2] = (float)Math.atan2(-R[8], R[10]); 1233 } 1234 return values; 1235 } 1236 1237 1238 /** 1239 * {@hide} 1240 */ 1241 public void onRotationChanged(int rotation) { 1242 synchronized(sListeners) { 1243 sRotation = rotation; 1244 } 1245 } 1246 1247 static int getRotation() { 1248 synchronized(sListeners) { 1249 return sRotation; 1250 } 1251 } 1252 1253 private class LegacyListener implements SensorEventListener { 1254 private float mValues[] = new float[6]; 1255 @SuppressWarnings("deprecation") 1256 private SensorListener mTarget; 1257 private int mSensors; 1258 private final LmsFilter mYawfilter = new LmsFilter(); 1259 1260 @SuppressWarnings("deprecation") 1261 LegacyListener(SensorListener target) { 1262 mTarget = target; 1263 mSensors = 0; 1264 } 1265 1266 void registerSensor(int legacyType) { 1267 mSensors |= legacyType; 1268 } 1269 1270 boolean unregisterSensor(int legacyType) { 1271 mSensors &= ~legacyType; 1272 int mask = SENSOR_ORIENTATION|SENSOR_ORIENTATION_RAW; 1273 if (((legacyType&mask)!=0) && ((mSensors&mask)!=0)) { 1274 return false; 1275 } 1276 return true; 1277 } 1278 1279 @SuppressWarnings("deprecation") 1280 public void onAccuracyChanged(Sensor sensor, int accuracy) { 1281 try { 1282 mTarget.onAccuracyChanged(sensor.getLegacyType(), accuracy); 1283 } catch (AbstractMethodError e) { 1284 // old app that doesn't implement this method 1285 // just ignore it. 1286 } 1287 } 1288 1289 @SuppressWarnings("deprecation") 1290 public void onSensorChanged(SensorEvent event) { 1291 final float v[] = mValues; 1292 v[0] = event.values[0]; 1293 v[1] = event.values[1]; 1294 v[2] = event.values[2]; 1295 int legacyType = event.sensor.getLegacyType(); 1296 mapSensorDataToWindow(legacyType, v, SensorManager.getRotation()); 1297 if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) { 1298 if ((mSensors & SENSOR_ORIENTATION_RAW)!=0) { 1299 mTarget.onSensorChanged(SENSOR_ORIENTATION_RAW, v); 1300 } 1301 if ((mSensors & SENSOR_ORIENTATION)!=0) { 1302 v[0] = mYawfilter.filter(event.timestamp, v[0]); 1303 mTarget.onSensorChanged(SENSOR_ORIENTATION, v); 1304 } 1305 } else { 1306 mTarget.onSensorChanged(legacyType, v); 1307 } 1308 } 1309 1310 /* 1311 * Helper function to convert the specified sensor's data to the windows's 1312 * coordinate space from the device's coordinate space. 1313 * 1314 * output: 3,4,5: values in the old API format 1315 * 0,1,2: transformed values in the old API format 1316 * 1317 */ 1318 private void mapSensorDataToWindow(int sensor, 1319 float[] values, int orientation) { 1320 float x = values[0]; 1321 float y = values[1]; 1322 float z = values[2]; 1323 1324 switch (sensor) { 1325 case SensorManager.SENSOR_ORIENTATION: 1326 case SensorManager.SENSOR_ORIENTATION_RAW: 1327 z = -z; 1328 break; 1329 case SensorManager.SENSOR_ACCELEROMETER: 1330 x = -x; 1331 y = -y; 1332 z = -z; 1333 break; 1334 case SensorManager.SENSOR_MAGNETIC_FIELD: 1335 x = -x; 1336 y = -y; 1337 break; 1338 } 1339 values[0] = x; 1340 values[1] = y; 1341 values[2] = z; 1342 values[3] = x; 1343 values[4] = y; 1344 values[5] = z; 1345 // TODO: add support for 180 and 270 orientations 1346 if (orientation == Surface.ROTATION_90) { 1347 switch (sensor) { 1348 case SENSOR_ACCELEROMETER: 1349 case SENSOR_MAGNETIC_FIELD: 1350 values[0] =-y; 1351 values[1] = x; 1352 values[2] = z; 1353 break; 1354 case SENSOR_ORIENTATION: 1355 case SENSOR_ORIENTATION_RAW: 1356 values[0] = x + ((x < 270) ? 90 : -270); 1357 values[1] = z; 1358 values[2] = y; 1359 break; 1360 } 1361 } 1362 } 1363 } 1364 1365 class LmsFilter { 1366 private static final int SENSORS_RATE_MS = 20; 1367 private static final int COUNT = 12; 1368 private static final float PREDICTION_RATIO = 1.0f/3.0f; 1369 private static final float PREDICTION_TIME = (SENSORS_RATE_MS*COUNT/1000.0f)*PREDICTION_RATIO; 1370 private float mV[] = new float[COUNT*2]; 1371 private float mT[] = new float[COUNT*2]; 1372 private int mIndex; 1373 1374 public LmsFilter() { 1375 mIndex = COUNT; 1376 } 1377 1378 public float filter(long time, float in) { 1379 float v = in; 1380 final float ns = 1.0f / 1000000000.0f; 1381 final float t = time*ns; 1382 float v1 = mV[mIndex]; 1383 if ((v-v1) > 180) { 1384 v -= 360; 1385 } else if ((v1-v) > 180) { 1386 v += 360; 1387 } 1388 /* Manage the circular buffer, we write the data twice spaced 1389 * by COUNT values, so that we don't have to copy the array 1390 * when it's full 1391 */ 1392 mIndex++; 1393 if (mIndex >= COUNT*2) 1394 mIndex = COUNT; 1395 mV[mIndex] = v; 1396 mT[mIndex] = t; 1397 mV[mIndex-COUNT] = v; 1398 mT[mIndex-COUNT] = t; 1399 1400 float A, B, C, D, E; 1401 float a, b; 1402 int i; 1403 1404 A = B = C = D = E = 0; 1405 for (i=0 ; i<COUNT-1 ; i++) { 1406 final int j = mIndex - 1 - i; 1407 final float Z = mV[j]; 1408 final float T = 0.5f*(mT[j] + mT[j+1]) - t; 1409 float dT = mT[j] - mT[j+1]; 1410 dT *= dT; 1411 A += Z*dT; 1412 B += T*(T*dT); 1413 C += (T*dT); 1414 D += Z*(T*dT); 1415 E += dT; 1416 } 1417 b = (A*B + C*D) / (E*B + C*C); 1418 a = (E*b - A) / C; 1419 float f = b + PREDICTION_TIME*a; 1420 1421 // Normalize 1422 f *= (1.0f / 360.0f); 1423 if (((f>=0)?f:-f) >= 0.5f) 1424 f = f - (float)Math.ceil(f + 0.5f) + 1.0f; 1425 if (f < 0) 1426 f += 1.0f; 1427 f *= 360.0f; 1428 return f; 1429 } 1430 } 1431 1432 1433 private static native void nativeClassInit(); 1434 1435 private static native int sensors_module_init(); 1436 private static native int sensors_module_get_next_sensor(Sensor sensor, int next); 1437 1438 // Used within this module from outside SensorManager, don't make private 1439 static native int sensors_data_init(); 1440 static native int sensors_data_uninit(); 1441 static native int sensors_data_open(FileDescriptor fd); 1442 static native int sensors_data_close(); 1443 static native int sensors_data_poll(float[] values, int[] status, long[] timestamp); 1444} 1445