SensorManager.java revision 15ab3eae2ec3d73b3e8aa60b33ae41445bf83f4b
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        if (listener == null) {
624            return false;
625        }
626        boolean result = false;
627        result = registerLegacyListener(SENSOR_ACCELEROMETER, Sensor.TYPE_ACCELEROMETER,
628                listener, sensors, rate) || result;
629        result = registerLegacyListener(SENSOR_MAGNETIC_FIELD, Sensor.TYPE_MAGNETIC_FIELD,
630                listener, sensors, rate) || result;
631        result = registerLegacyListener(SENSOR_ORIENTATION_RAW, Sensor.TYPE_ORIENTATION,
632                listener, sensors, rate) || result;
633        result = registerLegacyListener(SENSOR_ORIENTATION, Sensor.TYPE_ORIENTATION,
634                listener, sensors, rate) || result;
635        result = registerLegacyListener(SENSOR_TEMPERATURE, Sensor.TYPE_TEMPERATURE,
636                listener, sensors, rate) || result;
637        return result;
638    }
639
640    @SuppressWarnings("deprecation")
641    private boolean registerLegacyListener(int legacyType, int type,
642            SensorListener listener, int sensors, int rate)
643    {
644        if (listener == null) {
645            return false;
646        }
647        boolean result = false;
648        // Are we activating this legacy sensor?
649        if ((sensors & legacyType) != 0) {
650            // if so, find a suitable Sensor
651            Sensor sensor = getDefaultSensor(type);
652            if (sensor != null) {
653                // If we don't already have one, create a LegacyListener
654                // to wrap this listener and process the events as
655                // they are expected by legacy apps.
656                LegacyListener legacyListener = null;
657                synchronized (mLegacyListenersMap) {
658                    legacyListener = mLegacyListenersMap.get(listener);
659                    if (legacyListener == null) {
660                        // we didn't find a LegacyListener for this client,
661                        // create one, and put it in our list.
662                        legacyListener = new LegacyListener(listener);
663                        mLegacyListenersMap.put(listener, legacyListener);
664                    }
665                }
666                // register this legacy sensor with this legacy listener
667                legacyListener.registerSensor(legacyType);
668                // and finally, register the legacy listener with the new apis
669                result = registerListener(legacyListener, sensor, rate);
670            }
671        }
672        return result;
673    }
674
675    /**
676     * Unregisters a listener for the sensors with which it is registered.
677     * @deprecated This method is deprecated, use
678     * {@link SensorManager#unregisterListener(SensorEventListener, Sensor)}
679     * instead.
680     *
681     * @param listener a SensorListener object
682     * @param sensors a bit masks of the sensors to unregister from
683     */
684    @Deprecated
685    public void unregisterListener(SensorListener listener, int sensors) {
686        unregisterLegacyListener(SENSOR_ACCELEROMETER, Sensor.TYPE_ACCELEROMETER,
687                listener, sensors);
688        unregisterLegacyListener(SENSOR_MAGNETIC_FIELD, Sensor.TYPE_MAGNETIC_FIELD,
689                listener, sensors);
690        unregisterLegacyListener(SENSOR_ORIENTATION_RAW, Sensor.TYPE_ORIENTATION,
691                listener, sensors);
692        unregisterLegacyListener(SENSOR_ORIENTATION, Sensor.TYPE_ORIENTATION,
693                listener, sensors);
694        unregisterLegacyListener(SENSOR_TEMPERATURE, Sensor.TYPE_TEMPERATURE,
695                listener, sensors);
696    }
697
698    @SuppressWarnings("deprecation")
699    private void unregisterLegacyListener(int legacyType, int type,
700            SensorListener listener, int sensors)
701    {
702        if (listener == null) {
703            return;
704        }
705        // do we know about this listener?
706        LegacyListener legacyListener = null;
707        synchronized (mLegacyListenersMap) {
708            legacyListener = mLegacyListenersMap.get(listener);
709        }
710        if (legacyListener != null) {
711            // Are we deactivating this legacy sensor?
712            if ((sensors & legacyType) != 0) {
713                // if so, find the corresponding Sensor
714                Sensor sensor = getDefaultSensor(type);
715                if (sensor != null) {
716                    // unregister this legacy sensor and if we don't
717                    // need the corresponding Sensor, unregister it too
718                    if (legacyListener.unregisterSensor(legacyType)) {
719                        // corresponding sensor not needed, unregister
720                        unregisterListener(legacyListener, sensor);
721                        // finally check if we still need the legacyListener
722                        // in our mapping, if not, get rid of it too.
723                        synchronized(sListeners) {
724                            boolean found = false;
725                            for (ListenerDelegate i : sListeners) {
726                                if (i.getListener() == legacyListener) {
727                                    found = true;
728                                    break;
729                                }
730                            }
731                            if (!found) {
732                                synchronized (mLegacyListenersMap) {
733                                    mLegacyListenersMap.remove(listener);
734                                }
735                            }
736                        }
737                    }
738                }
739            }
740        }
741    }
742
743    /**
744     * Unregisters a listener for all sensors.
745     * @deprecated This method is deprecated, use
746     * {@link SensorManager#unregisterListener(SensorEventListener)}
747     * instead.
748     *
749     * @param listener a SensorListener object
750     */
751    @Deprecated
752    public void unregisterListener(SensorListener listener) {
753        unregisterListener(listener, SENSOR_ALL | SENSOR_ORIENTATION_RAW);
754    }
755
756    /**
757     * Unregisters a listener for the sensors with which it is registered.
758     *
759     * @param listener a SensorEventListener object
760     * @param sensor the sensor to unregister from
761     *
762     */
763    public void unregisterListener(SensorEventListener listener, Sensor sensor) {
764        unregisterListener((Object)listener, sensor);
765    }
766
767    /**
768     * Unregisters a listener for all sensors.
769     *
770     * @param listener a SensorListener object
771     *
772     */
773    public void unregisterListener(SensorEventListener listener) {
774        unregisterListener((Object)listener);
775    }
776
777
778    /**
779     * Registers a {@link android.hardware.SensorEventListener SensorEventListener}
780     * for the given sensor.
781     *
782     * @param listener A {@link android.hardware.SensorEventListener SensorEventListener} object.
783     * @param sensor The {@link android.hardware.Sensor Sensor} to register to.
784     * @param rate The rate {@link android.hardware.SensorEvent sensor events} are delivered at.
785     * This is only a hint to the system. Events may be received faster or
786     * slower than the specified rate. Usually events are received faster.
787     *
788     * @return true if the sensor is supported and successfully enabled.
789     *
790     */
791    public boolean registerListener(SensorEventListener listener, Sensor sensor, int rate) {
792        return registerListener(listener, sensor, rate, null);
793    }
794
795    /**
796     * Registers a {@link android.hardware.SensorEventListener SensorEventListener}
797     * for the given sensor.
798     *
799     * @param listener A {@link android.hardware.SensorEventListener SensorEventListener} object.
800     * @param sensor The {@link android.hardware.Sensor Sensor} to register to.
801     * @param rate The rate {@link android.hardware.SensorEvent sensor events} are delivered at.
802     * This is only a hint to the system. Events may be received faster or
803     * slower than the specified rate. Usually events are received faster.
804     * @param handler The {@link android.os.Handler Handler} the
805     * {@link android.hardware.SensorEvent sensor events} will be delivered to.
806     *
807     * @return true if the sensor is supported and successfully enabled.
808     *
809     */
810    public boolean registerListener(SensorEventListener listener, Sensor sensor, int rate,
811            Handler handler) {
812        if (listener == null || sensor == null) {
813            return false;
814        }
815        boolean result;
816        int delay = -1;
817        switch (rate) {
818            case SENSOR_DELAY_FASTEST:
819                delay = 0;
820                break;
821            case SENSOR_DELAY_GAME:
822                delay = 20;
823                break;
824            case SENSOR_DELAY_UI:
825                delay = 60;
826                break;
827            case SENSOR_DELAY_NORMAL:
828                delay = 200;
829                break;
830            default:
831                return false;
832        }
833
834        try {
835            synchronized (sListeners) {
836                ListenerDelegate l = null;
837                for (ListenerDelegate i : sListeners) {
838                    if (i.getListener() == listener) {
839                        l = i;
840                        break;
841                    }
842                }
843
844                String name = sensor.getName();
845                int handle = sensor.getHandle();
846                if (l == null) {
847                    l = new ListenerDelegate(listener, sensor, handler);
848                    result = mSensorService.enableSensor(l, name, handle, delay);
849                    if (result) {
850                        sListeners.add(l);
851                        sListeners.notify();
852                    }
853                    if (!sListeners.isEmpty()) {
854                        sSensorThread.startLocked(mSensorService);
855                    }
856                } else {
857                    result = mSensorService.enableSensor(l, name, handle, delay);
858                    if (result) {
859                        l.addSensor(sensor);
860                    }
861                }
862            }
863        } catch (RemoteException e) {
864            Log.e(TAG, "RemoteException in registerListener: ", e);
865            result = false;
866        }
867        return result;
868    }
869
870    private void unregisterListener(Object listener, Sensor sensor) {
871        if (listener == null || sensor == null) {
872            return;
873        }
874        try {
875            synchronized (sListeners) {
876                final int size = sListeners.size();
877                for (int i=0 ; i<size ; i++) {
878                    ListenerDelegate l = sListeners.get(i);
879                    if (l.getListener() == listener) {
880                        // disable these sensors
881                        String name = sensor.getName();
882                        int handle = sensor.getHandle();
883                        mSensorService.enableSensor(l, name, handle, SENSOR_DISABLE);
884                        // if we have no more sensors enabled on this listener,
885                        // take it off the list.
886                        if (l.removeSensor(sensor) == 0) {
887                            sListeners.remove(i);
888                        }
889                        break;
890                    }
891                }
892            }
893        } catch (RemoteException e) {
894            Log.e(TAG, "RemoteException in unregisterListener: ", e);
895        }
896    }
897
898    private void unregisterListener(Object listener) {
899        if (listener == null) {
900            return;
901        }
902        try {
903            synchronized (sListeners) {
904                final int size = sListeners.size();
905                for (int i=0 ; i<size ; i++) {
906                    ListenerDelegate l = sListeners.get(i);
907                    if (l.getListener() == listener) {
908                        // disable all sensors for this listener
909                        for (Sensor sensor : l.getSensors()) {
910                            String name = sensor.getName();
911                            int handle = sensor.getHandle();
912                            mSensorService.enableSensor(l, name, handle, SENSOR_DISABLE);
913                        }
914                        sListeners.remove(i);
915                        break;
916                    }
917                }
918            }
919        } catch (RemoteException e) {
920            Log.e(TAG, "RemoteException in unregisterListener: ", e);
921        }
922    }
923
924    /**
925     * Computes the inclination matrix <b>I</b> as well as the rotation
926     * matrix <b>R</b> transforming a vector from the
927     * device coordinate system to the world's coordinate system which is
928     * defined as a direct orthonormal basis, where:
929     *
930     * <li>X is defined as the vector product <b>Y.Z</b> (It is tangential to
931     * the ground at the device's current location and roughly points East).</li>
932     * <li>Y is tangential to the ground at the device's current location and
933     * points towards the magnetic North Pole.</li>
934     * <li>Z points towards the sky and is perpendicular to the ground.</li>
935     * <p>
936     * <hr>
937     * <p>By definition:
938     * <p>[0 0 g] = <b>R</b> * <b>gravity</b> (g = magnitude of gravity)
939     * <p>[0 m 0] = <b>I</b> * <b>R</b> * <b>geomagnetic</b>
940     * (m = magnitude of geomagnetic field)
941     * <p><b>R</b> is the identity matrix when the device is aligned with the
942     * world's coordinate system, that is, when the device's X axis points
943     * toward East, the Y axis points to the North Pole and the device is facing
944     * the sky.
945     *
946     * <p><b>I</b> is a rotation matrix transforming the geomagnetic
947     * vector into the same coordinate space as gravity (the world's coordinate
948     * space). <b>I</b> is a simple rotation around the X axis.
949     * The inclination angle in radians can be computed with
950     * {@link #getInclination}.
951     * <hr>
952     *
953     * <p> Each matrix is returned either as a 3x3 or 4x4 row-major matrix
954     * depending on the length of the passed array:
955     * <p><u>If the array length is 16:</u>
956     * <pre>
957     *   /  M[ 0]   M[ 1]   M[ 2]   M[ 3]  \
958     *   |  M[ 4]   M[ 5]   M[ 6]   M[ 7]  |
959     *   |  M[ 8]   M[ 9]   M[10]   M[11]  |
960     *   \  M[12]   M[13]   M[14]   M[15]  /
961     *</pre>
962     * This matrix is ready to be used by OpenGL ES's
963     * {@link javax.microedition.khronos.opengles.GL10#glLoadMatrixf(float[], int)
964     * glLoadMatrixf(float[], int)}.
965     * <p>Note that because OpenGL matrices are column-major matrices you must
966     * transpose the matrix before using it. However, since the matrix is a
967     * rotation matrix, its transpose is also its inverse, conveniently, it is
968     * often the inverse of the rotation that is needed for rendering; it can
969     * therefore be used with OpenGL ES directly.
970     * <p>
971     * Also note that the returned matrices always have this form:
972     * <pre>
973     *   /  M[ 0]   M[ 1]   M[ 2]   0  \
974     *   |  M[ 4]   M[ 5]   M[ 6]   0  |
975     *   |  M[ 8]   M[ 9]   M[10]   0  |
976     *   \      0       0       0   1  /
977     *</pre>
978     * <p><u>If the array length is 9:</u>
979     * <pre>
980     *   /  M[ 0]   M[ 1]   M[ 2]  \
981     *   |  M[ 3]   M[ 4]   M[ 5]  |
982     *   \  M[ 6]   M[ 7]   M[ 8]  /
983     *</pre>
984     *
985     * <hr>
986     * <p>The inverse of each matrix can be computed easily by taking its
987     * transpose.
988     *
989     * <p>The matrices returned by this function are meaningful only when the
990     * device is not free-falling and it is not close to the magnetic north.
991     * If the device is accelerating, or placed into a strong magnetic field,
992     * the returned matrices may be inaccurate.
993     *
994     * @param R is an array of 9 floats holding the rotation matrix <b>R</b>
995     * when this function returns. R can be null.<p>
996     * @param I is an array of 9 floats holding the rotation matrix <b>I</b>
997     * when this function returns. I can be null.<p>
998     * @param gravity is an array of 3 floats containing the gravity vector
999     * expressed in the device's coordinate. You can simply use the
1000     * {@link android.hardware.SensorEvent#values values}
1001     * returned by a {@link android.hardware.SensorEvent SensorEvent} of a
1002     * {@link android.hardware.Sensor Sensor} of type
1003     * {@link android.hardware.Sensor#TYPE_ACCELEROMETER TYPE_ACCELEROMETER}.<p>
1004     * @param geomagnetic is an array of 3 floats containing the geomagnetic
1005     * vector expressed in the device's coordinate. You can simply use the
1006     * {@link android.hardware.SensorEvent#values values}
1007     * returned by a {@link android.hardware.SensorEvent SensorEvent} of a
1008     * {@link android.hardware.Sensor Sensor} of type
1009     * {@link android.hardware.Sensor#TYPE_MAGNETIC_FIELD TYPE_MAGNETIC_FIELD}.
1010     * @return
1011     *   true on success<p>
1012     *   false on failure (for instance, if the device is in free fall).
1013     *   On failure the output matrices are not modified.
1014     */
1015
1016    public static boolean getRotationMatrix(float[] R, float[] I,
1017            float[] gravity, float[] geomagnetic) {
1018        // TODO: move this to native code for efficiency
1019        float Ax = gravity[0];
1020        float Ay = gravity[1];
1021        float Az = gravity[2];
1022        final float Ex = geomagnetic[0];
1023        final float Ey = geomagnetic[1];
1024        final float Ez = geomagnetic[2];
1025        float Hx = Ey*Az - Ez*Ay;
1026        float Hy = Ez*Ax - Ex*Az;
1027        float Hz = Ex*Ay - Ey*Ax;
1028        final float normH = (float)Math.sqrt(Hx*Hx + Hy*Hy + Hz*Hz);
1029        if (normH < 0.1f) {
1030            // device is close to free fall (or in space?), or close to
1031            // magnetic north pole. Typical values are  > 100.
1032            return false;
1033        }
1034        final float invH = 1.0f / normH;
1035        Hx *= invH;
1036        Hy *= invH;
1037        Hz *= invH;
1038        final float invA = 1.0f / (float)Math.sqrt(Ax*Ax + Ay*Ay + Az*Az);
1039        Ax *= invA;
1040        Ay *= invA;
1041        Az *= invA;
1042        final float Mx = Ay*Hz - Az*Hy;
1043        final float My = Az*Hx - Ax*Hz;
1044        final float Mz = Ax*Hy - Ay*Hx;
1045        if (R != null) {
1046            if (R.length == 9) {
1047                R[0] = Hx;     R[1] = Hy;     R[2] = Hz;
1048                R[3] = Mx;     R[4] = My;     R[5] = Mz;
1049                R[6] = Ax;     R[7] = Ay;     R[8] = Az;
1050            } else if (R.length == 16) {
1051                R[0]  = Hx;    R[1]  = Hy;    R[2]  = Hz;   R[3]  = 0;
1052                R[4]  = Mx;    R[5]  = My;    R[6]  = Mz;   R[7]  = 0;
1053                R[8]  = Ax;    R[9]  = Ay;    R[10] = Az;   R[11] = 0;
1054                R[12] = 0;     R[13] = 0;     R[14] = 0;    R[15] = 1;
1055            }
1056        }
1057        if (I != null) {
1058            // compute the inclination matrix by projecting the geomagnetic
1059            // vector onto the Z (gravity) and X (horizontal component
1060            // of geomagnetic vector) axes.
1061            final float invE = 1.0f / (float)Math.sqrt(Ex*Ex + Ey*Ey + Ez*Ez);
1062            final float c = (Ex*Mx + Ey*My + Ez*Mz) * invE;
1063            final float s = (Ex*Ax + Ey*Ay + Ez*Az) * invE;
1064            if (I.length == 9) {
1065                I[0] = 1;     I[1] = 0;     I[2] = 0;
1066                I[3] = 0;     I[4] = c;     I[5] = s;
1067                I[6] = 0;     I[7] =-s;     I[8] = c;
1068            } else if (I.length == 16) {
1069                I[0] = 1;     I[1] = 0;     I[2] = 0;
1070                I[4] = 0;     I[5] = c;     I[6] = s;
1071                I[8] = 0;     I[9] =-s;     I[10]= c;
1072                I[3] = I[7] = I[11] = I[12] = I[13] = I[14] = 0;
1073                I[15] = 1;
1074            }
1075        }
1076        return true;
1077    }
1078
1079    /**
1080     * Computes the geomagnetic inclination angle in radians from the
1081     * inclination matrix <b>I</b> returned by {@link #getRotationMatrix}.
1082     * @param I inclination matrix see {@link #getRotationMatrix}.
1083     * @return The geomagnetic inclination angle in radians.
1084     */
1085    public static float getInclination(float[] I) {
1086        if (I.length == 9) {
1087            return (float)Math.atan2(I[5], I[4]);
1088        } else {
1089            return (float)Math.atan2(I[6], I[5]);
1090        }
1091    }
1092
1093    /**
1094     * Rotates the supplied rotation matrix so it is expressed in a
1095     * different coordinate system. This is typically used when an application
1096     * needs to compute the three orientation angles of the device (see
1097     * {@link #getOrientation}) in a different coordinate system.
1098     *
1099     * <p>When the rotation matrix is used for drawing (for instance with
1100     * OpenGL ES), it usually <b>doesn't need</b> to be transformed by this
1101     * function, unless the screen is physically rotated, such as when used
1102     * in landscape mode.
1103     *
1104     * <p><u>Examples:</u><p>
1105     *
1106     * <li>Using the camera (Y axis along the camera's axis) for an augmented
1107     * reality application where the rotation angles are needed :</li><p>
1108     *
1109     * <code>remapCoordinateSystem(inR, AXIS_X, AXIS_Z, outR);</code><p>
1110     *
1111     * <li>Using the device as a mechanical compass in landscape mode:</li><p>
1112     *
1113     * <code>remapCoordinateSystem(inR, AXIS_Y, AXIS_MINUS_X, outR);</code><p>
1114     *
1115     * Beware of the above example. This call is needed only if the device is
1116     * physically used in landscape mode to calculate the rotation angles (see
1117     * {@link #getOrientation}).
1118     * If the rotation matrix is also used for rendering, it may not need to
1119     * be transformed, for instance if your {@link android.app.Activity
1120     * Activity} is running in landscape mode.
1121     *
1122     * <p>Since the resulting coordinate system is orthonormal, only two axes
1123     * need to be specified.
1124     *
1125     * @param inR the rotation matrix to be transformed. Usually it is the
1126     * matrix returned by {@link #getRotationMatrix}.
1127     * @param X defines on which world axis and direction the X axis of the
1128     *        device is mapped.
1129     * @param Y defines on which world axis and direction the Y axis of the
1130     *        device is mapped.
1131     * @param outR the transformed rotation matrix. inR and outR can be the same
1132     *        array, but it is not recommended for performance reason.
1133     * @return true on success. false if the input parameters are incorrect, for
1134     * instance if X and Y define the same axis. Or if inR and outR don't have
1135     * the same length.
1136     */
1137
1138    public static boolean remapCoordinateSystem(float[] inR, int X, int Y,
1139            float[] outR)
1140    {
1141        if (inR == outR) {
1142            final float[] temp = mTempMatrix;
1143            synchronized(temp) {
1144                // we don't expect to have a lot of contention
1145                if (remapCoordinateSystemImpl(inR, X, Y, temp)) {
1146                    final int size = outR.length;
1147                    for (int i=0 ; i<size ; i++)
1148                        outR[i] = temp[i];
1149                    return true;
1150                }
1151            }
1152        }
1153        return remapCoordinateSystemImpl(inR, X, Y, outR);
1154    }
1155
1156    private static boolean remapCoordinateSystemImpl(float[] inR, int X, int Y,
1157            float[] outR)
1158    {
1159        /*
1160         * X and Y define a rotation matrix 'r':
1161         *
1162         *  (X==1)?((X&0x80)?-1:1):0    (X==2)?((X&0x80)?-1:1):0    (X==3)?((X&0x80)?-1:1):0
1163         *  (Y==1)?((Y&0x80)?-1:1):0    (Y==2)?((Y&0x80)?-1:1):0    (Y==3)?((X&0x80)?-1:1):0
1164         *                              r[0] ^ r[1]
1165         *
1166         * where the 3rd line is the vector product of the first 2 lines
1167         *
1168         */
1169
1170        final int length = outR.length;
1171        if (inR.length != length)
1172            return false;   // invalid parameter
1173        if ((X & 0x7C)!=0 || (Y & 0x7C)!=0)
1174            return false;   // invalid parameter
1175        if (((X & 0x3)==0) || ((Y & 0x3)==0))
1176            return false;   // no axis specified
1177        if ((X & 0x3) == (Y & 0x3))
1178            return false;   // same axis specified
1179
1180        // Z is "the other" axis, its sign is either +/- sign(X)*sign(Y)
1181        // this can be calculated by exclusive-or'ing X and Y; except for
1182        // the sign inversion (+/-) which is calculated below.
1183        int Z = X ^ Y;
1184
1185        // extract the axis (remove the sign), offset in the range 0 to 2.
1186        final int x = (X & 0x3)-1;
1187        final int y = (Y & 0x3)-1;
1188        final int z = (Z & 0x3)-1;
1189
1190        // compute the sign of Z (whether it needs to be inverted)
1191        final int axis_y = (z+1)%3;
1192        final int axis_z = (z+2)%3;
1193        if (((x^axis_y)|(y^axis_z)) != 0)
1194            Z ^= 0x80;
1195
1196        final boolean sx = (X>=0x80);
1197        final boolean sy = (Y>=0x80);
1198        final boolean sz = (Z>=0x80);
1199
1200        // Perform R * r, in avoiding actual muls and adds.
1201        final int rowLength = ((length==16)?4:3);
1202        for (int j=0 ; j<3 ; j++) {
1203            final int offset = j*rowLength;
1204            for (int i=0 ; i<3 ; i++) {
1205                if (x==i)   outR[offset+i] = sx ? -inR[offset+0] : inR[offset+0];
1206                if (y==i)   outR[offset+i] = sy ? -inR[offset+1] : inR[offset+1];
1207                if (z==i)   outR[offset+i] = sz ? -inR[offset+2] : inR[offset+2];
1208            }
1209        }
1210        if (length == 16) {
1211            outR[3] = outR[7] = outR[11] = outR[12] = outR[13] = outR[14] = 0;
1212            outR[15] = 1;
1213        }
1214        return true;
1215    }
1216
1217    /**
1218     * Computes the device's orientation based on the rotation matrix.
1219     * <p> When it returns, the array values is filled with the result:
1220     * <li>values[0]: <i>azimuth</i>, rotation around the Z axis.</li>
1221     * <li>values[1]: <i>pitch</i>, rotation around the X axis.</li>
1222     * <li>values[2]: <i>roll</i>, rotation around the Y axis.</li>
1223     * <p>
1224     *
1225     * @param R rotation matrix see {@link #getRotationMatrix}.
1226     * @param values an array of 3 floats to hold the result.
1227     * @return The array values passed as argument.
1228     */
1229    public static float[] getOrientation(float[] R, float values[]) {
1230        /*
1231         * 4x4 (length=16) case:
1232         *   /  R[ 0]   R[ 1]   R[ 2]   0  \
1233         *   |  R[ 4]   R[ 5]   R[ 6]   0  |
1234         *   |  R[ 8]   R[ 9]   R[10]   0  |
1235         *   \      0       0       0   1  /
1236         *
1237         * 3x3 (length=9) case:
1238         *   /  R[ 0]   R[ 1]   R[ 2]  \
1239         *   |  R[ 3]   R[ 4]   R[ 5]  |
1240         *   \  R[ 6]   R[ 7]   R[ 8]  /
1241         *
1242         */
1243        if (R.length == 9) {
1244            values[0] = (float)Math.atan2(R[1], R[4]);
1245            values[1] = (float)Math.asin(-R[7]);
1246            values[2] = (float)Math.atan2(-R[6], R[8]);
1247        } else {
1248            values[0] = (float)Math.atan2(R[1], R[5]);
1249            values[1] = (float)Math.asin(-R[9]);
1250            values[2] = (float)Math.atan2(-R[8], R[10]);
1251        }
1252        return values;
1253    }
1254
1255
1256    /**
1257     * {@hide}
1258     */
1259    public void onRotationChanged(int rotation) {
1260        synchronized(sListeners) {
1261            sRotation  = rotation;
1262        }
1263    }
1264
1265    static int getRotation() {
1266        synchronized(sListeners) {
1267            return sRotation;
1268        }
1269    }
1270
1271    private class LegacyListener implements SensorEventListener {
1272        private float mValues[] = new float[6];
1273        @SuppressWarnings("deprecation")
1274        private SensorListener mTarget;
1275        private int mSensors;
1276        private final LmsFilter mYawfilter = new LmsFilter();
1277
1278        @SuppressWarnings("deprecation")
1279        LegacyListener(SensorListener target) {
1280            mTarget = target;
1281            mSensors = 0;
1282        }
1283
1284        void registerSensor(int legacyType) {
1285            mSensors |= legacyType;
1286        }
1287
1288        boolean unregisterSensor(int legacyType) {
1289            mSensors &= ~legacyType;
1290            int mask = SENSOR_ORIENTATION|SENSOR_ORIENTATION_RAW;
1291            if (((legacyType&mask)!=0) && ((mSensors&mask)!=0)) {
1292                return false;
1293            }
1294            return true;
1295        }
1296
1297        @SuppressWarnings("deprecation")
1298        public void onAccuracyChanged(Sensor sensor, int accuracy) {
1299            try {
1300                mTarget.onAccuracyChanged(sensor.getLegacyType(), accuracy);
1301            } catch (AbstractMethodError e) {
1302                // old app that doesn't implement this method
1303                // just ignore it.
1304            }
1305        }
1306
1307        @SuppressWarnings("deprecation")
1308        public void onSensorChanged(SensorEvent event) {
1309            final float v[] = mValues;
1310            v[0] = event.values[0];
1311            v[1] = event.values[1];
1312            v[2] = event.values[2];
1313            int legacyType = event.sensor.getLegacyType();
1314            mapSensorDataToWindow(legacyType, v, SensorManager.getRotation());
1315            if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
1316                if ((mSensors & SENSOR_ORIENTATION_RAW)!=0) {
1317                    mTarget.onSensorChanged(SENSOR_ORIENTATION_RAW, v);
1318                }
1319                if ((mSensors & SENSOR_ORIENTATION)!=0) {
1320                    v[0] = mYawfilter.filter(event.timestamp, v[0]);
1321                    mTarget.onSensorChanged(SENSOR_ORIENTATION, v);
1322                }
1323            } else {
1324                mTarget.onSensorChanged(legacyType, v);
1325            }
1326        }
1327
1328        /*
1329         * Helper function to convert the specified sensor's data to the windows's
1330         * coordinate space from the device's coordinate space.
1331         *
1332         * output: 3,4,5: values in the old API format
1333         *         0,1,2: transformed values in the old API format
1334         *
1335         */
1336        private void mapSensorDataToWindow(int sensor,
1337                float[] values, int orientation) {
1338            float x = values[0];
1339            float y = values[1];
1340            float z = values[2];
1341
1342            switch (sensor) {
1343                case SensorManager.SENSOR_ORIENTATION:
1344                case SensorManager.SENSOR_ORIENTATION_RAW:
1345                    z = -z;
1346                    break;
1347                case SensorManager.SENSOR_ACCELEROMETER:
1348                    x = -x;
1349                    y = -y;
1350                    z = -z;
1351                    break;
1352                case SensorManager.SENSOR_MAGNETIC_FIELD:
1353                    x = -x;
1354                    y = -y;
1355                    break;
1356            }
1357            values[0] = x;
1358            values[1] = y;
1359            values[2] = z;
1360            values[3] = x;
1361            values[4] = y;
1362            values[5] = z;
1363            // TODO: add support for 180 and 270 orientations
1364            if (orientation == Surface.ROTATION_90) {
1365                switch (sensor) {
1366                    case SENSOR_ACCELEROMETER:
1367                    case SENSOR_MAGNETIC_FIELD:
1368                        values[0] =-y;
1369                        values[1] = x;
1370                        values[2] = z;
1371                        break;
1372                    case SENSOR_ORIENTATION:
1373                    case SENSOR_ORIENTATION_RAW:
1374                        values[0] = x + ((x < 270) ? 90 : -270);
1375                        values[1] = z;
1376                        values[2] = y;
1377                        break;
1378                }
1379            }
1380        }
1381    }
1382
1383    class LmsFilter {
1384        private static final int SENSORS_RATE_MS = 20;
1385        private static final int COUNT = 12;
1386        private static final float PREDICTION_RATIO = 1.0f/3.0f;
1387        private static final float PREDICTION_TIME = (SENSORS_RATE_MS*COUNT/1000.0f)*PREDICTION_RATIO;
1388        private float mV[] = new float[COUNT*2];
1389        private float mT[] = new float[COUNT*2];
1390        private int mIndex;
1391
1392        public LmsFilter() {
1393            mIndex = COUNT;
1394        }
1395
1396        public float filter(long time, float in) {
1397            float v = in;
1398            final float ns = 1.0f / 1000000000.0f;
1399            final float t = time*ns;
1400            float v1 = mV[mIndex];
1401            if ((v-v1) > 180) {
1402                v -= 360;
1403            } else if ((v1-v) > 180) {
1404                v += 360;
1405            }
1406            /* Manage the circular buffer, we write the data twice spaced
1407             * by COUNT values, so that we don't have to copy the array
1408             * when it's full
1409             */
1410            mIndex++;
1411            if (mIndex >= COUNT*2)
1412                mIndex = COUNT;
1413            mV[mIndex] = v;
1414            mT[mIndex] = t;
1415            mV[mIndex-COUNT] = v;
1416            mT[mIndex-COUNT] = t;
1417
1418            float A, B, C, D, E;
1419            float a, b;
1420            int i;
1421
1422            A = B = C = D = E = 0;
1423            for (i=0 ; i<COUNT-1 ; i++) {
1424                final int j = mIndex - 1 - i;
1425                final float Z = mV[j];
1426                final float T = 0.5f*(mT[j] + mT[j+1]) - t;
1427                float dT = mT[j] - mT[j+1];
1428                dT *= dT;
1429                A += Z*dT;
1430                B += T*(T*dT);
1431                C +=   (T*dT);
1432                D += Z*(T*dT);
1433                E += dT;
1434            }
1435            b = (A*B + C*D) / (E*B + C*C);
1436            a = (E*b - A) / C;
1437            float f = b + PREDICTION_TIME*a;
1438
1439            // Normalize
1440            f *= (1.0f / 360.0f);
1441            if (((f>=0)?f:-f) >= 0.5f)
1442                f = f - (float)Math.ceil(f + 0.5f) + 1.0f;
1443            if (f < 0)
1444                f += 1.0f;
1445            f *= 360.0f;
1446            return f;
1447        }
1448    }
1449
1450
1451    private static native void nativeClassInit();
1452
1453    private static native int sensors_module_init();
1454    private static native int sensors_module_get_next_sensor(Sensor sensor, int next);
1455
1456    // Used within this module from outside SensorManager, don't make private
1457    static native int sensors_data_init();
1458    static native int sensors_data_uninit();
1459    static native int sensors_data_open(FileDescriptor fd);
1460    static native int sensors_data_close();
1461    static native int sensors_data_poll(float[] values, int[] status, long[] timestamp);
1462}
1463