SensorManager.java revision f013e1afd1e68af5e3b868c26a653bbfb39538f8
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);
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                if (l == null) {
833                    l = new ListenerDelegate(listener, sensor, handler);
834                    result = mSensorService.enableSensor(l, sensor.getHandle(), delay);
835                    if (result) {
836                        sListeners.add(l);
837                        sListeners.notify();
838                    }
839                    if (!sListeners.isEmpty()) {
840                        sSensorThread.startLocked(mSensorService);
841                    }
842                } else {
843                    result = mSensorService.enableSensor(l, sensor.getHandle(), delay);
844                    if (result) {
845                        l.addSensor(sensor);
846                    }
847                }
848            }
849        } catch (RemoteException e) {
850            Log.e(TAG, "RemoteException in registerListener: ", e);
851            result = false;
852        }
853        return result;
854    }
855
856    private void unregisterListener(Object listener, Sensor sensor) {
857        try {
858            synchronized (sListeners) {
859                final int size = sListeners.size();
860                for (int i=0 ; i<size ; i++) {
861                    ListenerDelegate l = sListeners.get(i);
862                    if (l.getListener() == listener) {
863                        // disable these sensors
864                        int handle = sensor.getHandle();
865                        mSensorService.enableSensor(l, handle, SENSOR_DISABLE);
866                        // if we have no more sensors enabled on this listener,
867                        // take it off the list.
868                        if (l.removeSensor(sensor) == 0) {
869                            sListeners.remove(i);
870                        }
871                        break;
872                    }
873                }
874            }
875        } catch (RemoteException e) {
876            Log.e(TAG, "RemoteException in unregisterListener: ", e);
877        }
878    }
879
880    private void unregisterListener(Object listener) {
881        try {
882            synchronized (sListeners) {
883                final int size = sListeners.size();
884                for (int i=0 ; i<size ; i++) {
885                    ListenerDelegate l = sListeners.get(i);
886                    if (l.getListener() == listener) {
887                        // disable all sensors for this listener
888                        for (Sensor sensor : l.getSensors()) {
889                            mSensorService.enableSensor(l, sensor.getHandle(), SENSOR_DISABLE);
890                        }
891                        sListeners.remove(i);
892                        break;
893                    }
894                }
895            }
896        } catch (RemoteException e) {
897            Log.e(TAG, "RemoteException in unregisterListener: ", e);
898        }
899    }
900
901    /**
902     * Computes the inclination matrix <b>I</b> as well as the rotation
903     * matrix <b>R</b> transforming a vector from the
904     * device coordinate system to the world's coordinate system which is
905     * defined as a direct orthonormal basis, where:
906     *
907     * <li>X is defined as the vector product <b>Y.Z</b> (It is tangential to
908     * the ground at the device's current location and roughly points East).</li>
909     * <li>Y is tangential to the ground at the device's current location and
910     * points towards the magnetic North Pole.</li>
911     * <li>Z points towards the sky and is perpendicular to the ground.</li>
912     * <p>
913     * <hr>
914     * <p>By definition:
915     * <p>[0 0 g] = <b>R</b> * <b>gravity</b> (g = magnitude of gravity)
916     * <p>[0 m 0] = <b>I</b> * <b>R</b> * <b>geomagnetic</b>
917     * (m = magnitude of geomagnetic field)
918     * <p><b>R</b> is the identity matrix when the device is aligned with the
919     * world's coordinate system, that is, when the device's X axis points
920     * toward East, the Y axis points to the North Pole and the device is facing
921     * the sky.
922     *
923     * <p><b>I</b> is a rotation matrix transforming the geomagnetic
924     * vector into the same coordinate space as gravity (the world's coordinate
925     * space). <b>I</b> is a simple rotation around the X axis.
926     * The inclination angle in radians can be computed with
927     * {@link #getInclination}.
928     * <hr>
929     *
930     * <p> Each matrix is returned either as a 3x3 or 4x4 row-major matrix
931     * depending on the length of the passed array:
932     * <p><u>If the array length is 16:</u>
933     * <pre>
934     *   /  M[ 0]   M[ 1]   M[ 2]   M[ 3]  \
935     *   |  M[ 4]   M[ 5]   M[ 6]   M[ 7]  |
936     *   |  M[ 8]   M[ 9]   M[10]   M[11]  |
937     *   \  M[12]   M[13]   M[14]   M[15]  /
938     *</pre>
939     * This matrix is ready to be used by OpenGL ES's
940     * {@link javax.microedition.khronos.opengles.GL10#glLoadMatrixf(float[], int)
941     * glLoadMatrixf(float[], int)}.
942     * <p>Note that because OpenGL matrices are column-major matrices you must
943     * transpose the matrix before using it. However, since the matrix is a
944     * rotation matrix, its transpose is also its inverse, conveniently, it is
945     * often the inverse of the rotation that is needed for rendering; it can
946     * therefore be used with OpenGL ES directly.
947     * <p>
948     * Also note that the returned matrices always have this form:
949     * <pre>
950     *   /  M[ 0]   M[ 1]   M[ 2]   0  \
951     *   |  M[ 4]   M[ 5]   M[ 6]   0  |
952     *   |  M[ 8]   M[ 9]   M[10]   0  |
953     *   \      0       0       0   1  /
954     *</pre>
955     * <p><u>If the array length is 9:</u>
956     * <pre>
957     *   /  M[ 0]   M[ 1]   M[ 2]  \
958     *   |  M[ 3]   M[ 4]   M[ 5]  |
959     *   \  M[ 6]   M[ 7]   M[ 8]  /
960     *</pre>
961     *
962     * <hr>
963     * <p>The inverse of each matrix can be computed easily by taking its
964     * transpose.
965     *
966     * <p>The matrices returned by this function are meaningful only when the
967     * device is not free-falling and it is not close to the magnetic north.
968     * If the device is accelerating, or placed into a strong magnetic field,
969     * the returned matrices may be inaccurate.
970     *
971     * @param R is an array of 9 floats holding the rotation matrix <b>R</b>
972     * when this function returns. R can be null.<p>
973     * @param I is an array of 9 floats holding the rotation matrix <b>I</b>
974     * when this function returns. I can be null.<p>
975     * @param gravity is an array of 3 floats containing the gravity vector
976     * expressed in the device's coordinate. You can simply use the
977     * {@link android.hardware.SensorEvent#values values}
978     * returned by a {@link android.hardware.SensorEvent SensorEvent} of a
979     * {@link android.hardware.Sensor Sensor} of type
980     * {@link android.hardware.Sensor#TYPE_ACCELEROMETER TYPE_ACCELEROMETER}.<p>
981     * @param geomagnetic is an array of 3 floats containing the geomagnetic
982     * vector expressed in the device's coordinate. You can simply use the
983     * {@link android.hardware.SensorEvent#values values}
984     * returned by a {@link android.hardware.SensorEvent SensorEvent} of a
985     * {@link android.hardware.Sensor Sensor} of type
986     * {@link android.hardware.Sensor#TYPE_MAGNETIC_FIELD TYPE_MAGNETIC_FIELD}.
987     * @return
988     *   true on success<p>
989     *   false on failure (for instance, if the device is in free fall).
990     *   On failure the output matrices are not modified.
991     */
992
993    public static boolean getRotationMatrix(float[] R, float[] I,
994            float[] gravity, float[] geomagnetic) {
995        // TODO: move this to native code for efficiency
996        float Ax = gravity[0];
997        float Ay = gravity[1];
998        float Az = gravity[2];
999        final float Ex = geomagnetic[0];
1000        final float Ey = geomagnetic[1];
1001        final float Ez = geomagnetic[2];
1002        float Hx = Ey*Az - Ez*Ay;
1003        float Hy = Ez*Ax - Ex*Az;
1004        float Hz = Ex*Ay - Ey*Ax;
1005        final float normH = (float)Math.sqrt(Hx*Hx + Hy*Hy + Hz*Hz);
1006        if (normH < 0.1f) {
1007            // device is close to free fall (or in space?), or close to
1008            // magnetic north pole. Typical values are  > 100.
1009            return false;
1010        }
1011        final float invH = 1.0f / normH;
1012        Hx *= invH;
1013        Hy *= invH;
1014        Hz *= invH;
1015        final float invA = 1.0f / (float)Math.sqrt(Ax*Ax + Ay*Ay + Az*Az);
1016        Ax *= invA;
1017        Ay *= invA;
1018        Az *= invA;
1019        final float Mx = Ay*Hz - Az*Hy;
1020        final float My = Az*Hx - Ax*Hz;
1021        final float Mz = Ax*Hy - Ay*Hx;
1022        if (R != null) {
1023            if (R.length == 9) {
1024                R[0] = Hx;     R[1] = Hy;     R[2] = Hz;
1025                R[3] = Mx;     R[4] = My;     R[5] = Mz;
1026                R[6] = Ax;     R[7] = Ay;     R[8] = Az;
1027            } else if (R.length == 16) {
1028                R[0]  = Hx;    R[1]  = Hy;    R[2]  = Hz;   R[3]  = 0;
1029                R[4]  = Mx;    R[5]  = My;    R[6]  = Mz;   R[7]  = 0;
1030                R[8]  = Ax;    R[9]  = Ay;    R[10] = Az;   R[11] = 0;
1031                R[12] = 0;     R[13] = 0;     R[14] = 0;    R[15] = 1;
1032            }
1033        }
1034        if (I != null) {
1035            // compute the inclination matrix by projecting the geomagnetic
1036            // vector onto the Z (gravity) and X (horizontal component
1037            // of geomagnetic vector) axes.
1038            final float invE = 1.0f / (float)Math.sqrt(Ex*Ex + Ey*Ey + Ez*Ez);
1039            final float c = (Ex*Mx + Ey*My + Ez*Mz) * invE;
1040            final float s = (Ex*Ax + Ey*Ay + Ez*Az) * invE;
1041            if (I.length == 9) {
1042                I[0] = 1;     I[1] = 0;     I[2] = 0;
1043                I[3] = 0;     I[4] = c;     I[5] = s;
1044                I[6] = 0;     I[7] =-s;     I[8] = c;
1045            } else if (I.length == 16) {
1046                I[0] = 1;     I[1] = 0;     I[2] = 0;
1047                I[4] = 0;     I[5] = c;     I[6] = s;
1048                I[8] = 0;     I[9] =-s;     I[10]= c;
1049                I[3] = I[7] = I[11] = I[12] = I[13] = I[14] = 0;
1050                I[15] = 1;
1051            }
1052        }
1053        return true;
1054    }
1055
1056    /**
1057     * Computes the geomagnetic inclination angle in radians from the
1058     * inclination matrix <b>I</b> returned by {@link #getRotationMatrix}.
1059     * @param I inclination matrix see {@link #getRotationMatrix}.
1060     * @return The geomagnetic inclination angle in radians.
1061     */
1062    public static float getInclination(float[] I) {
1063        if (I.length == 9) {
1064            return (float)Math.atan2(I[5], I[4]);
1065        } else {
1066            return (float)Math.atan2(I[6], I[5]);
1067        }
1068    }
1069
1070    /**
1071     * Rotates the supplied rotation matrix so it is expressed in a
1072     * different coordinate system. This is typically used when an application
1073     * needs to compute the three orientation angles of the device (see
1074     * {@link #getOrientation}) in a different coordinate system.
1075     *
1076     * <p>When the rotation matrix is used for drawing (for instance with
1077     * OpenGL ES), it usually <b>doesn't need</b> to be transformed by this
1078     * function, unless the screen is physically rotated, such as when used
1079     * in landscape mode.
1080     *
1081     * <p><u>Examples:</u><p>
1082     *
1083     * <li>Using the camera (Y axis along the camera's axis) for an augmented
1084     * reality application where the rotation angles are needed :</li><p>
1085     *
1086     * <code>remapCoordinateSystem(inR, AXIS_X, AXIS_Z, outR);</code><p>
1087     *
1088     * <li>Using the device as a mechanical compass in landscape mode:</li><p>
1089     *
1090     * <code>remapCoordinateSystem(inR, AXIS_Y, AXIS_MINUS_X, outR);</code><p>
1091     *
1092     * Beware of the above example. This call is needed only if the device is
1093     * physically used in landscape mode to calculate the rotation angles (see
1094     * {@link #getOrientation}).
1095     * If the rotation matrix is also used for rendering, it may not need to
1096     * be transformed, for instance if your {@link android.app.Activity
1097     * Activity} is running in landscape mode.
1098     *
1099     * <p>Since the resulting coordinate system is orthonormal, only two axes
1100     * need to be specified.
1101     *
1102     * @param inR the rotation matrix to be transformed. Usually it is the
1103     * matrix returned by {@link #getRotationMatrix}.
1104     * @param X defines on which world axis and direction the X axis of the
1105     *        device is mapped.
1106     * @param Y defines on which world axis and direction the Y axis of the
1107     *        device is mapped.
1108     * @param outR the transformed rotation matrix. inR and outR can be the same
1109     *        array, but it is not recommended for performance reason.
1110     * @return true on success. false if the input parameters are incorrect, for
1111     * instance if X and Y define the same axis. Or if inR and outR don't have
1112     * the same length.
1113     */
1114
1115    public static boolean remapCoordinateSystem(float[] inR, int X, int Y,
1116            float[] outR)
1117    {
1118        if (inR == outR) {
1119            final float[] temp = mTempMatrix;
1120            synchronized(temp) {
1121                // we don't expect to have a lot of contention
1122                if (remapCoordinateSystemImpl(inR, X, Y, temp)) {
1123                    final int size = outR.length;
1124                    for (int i=0 ; i<size ; i++)
1125                        outR[i] = temp[i];
1126                    return true;
1127                }
1128            }
1129        }
1130        return remapCoordinateSystemImpl(inR, X, Y, outR);
1131    }
1132
1133    private static boolean remapCoordinateSystemImpl(float[] inR, int X, int Y,
1134            float[] outR)
1135    {
1136        /*
1137         * X and Y define a rotation matrix 'r':
1138         *
1139         *  (X==1)?((X&0x80)?-1:1):0    (X==2)?((X&0x80)?-1:1):0    (X==3)?((X&0x80)?-1:1):0
1140         *  (Y==1)?((Y&0x80)?-1:1):0    (Y==2)?((Y&0x80)?-1:1):0    (Y==3)?((X&0x80)?-1:1):0
1141         *                              r[0] ^ r[1]
1142         *
1143         * where the 3rd line is the vector product of the first 2 lines
1144         *
1145         */
1146
1147        final int length = outR.length;
1148        if (inR.length != length)
1149            return false;   // invalid parameter
1150        if ((X & 0x7C)!=0 || (Y & 0x7C)!=0)
1151            return false;   // invalid parameter
1152        if (((X & 0x3)==0) || ((Y & 0x3)==0))
1153            return false;   // no axis specified
1154        if ((X & 0x3) == (Y & 0x3))
1155            return false;   // same axis specified
1156
1157        // Z is "the other" axis, its sign is either +/- sign(X)*sign(Y)
1158        // this can be calculated by exclusive-or'ing X and Y; except for
1159        // the sign inversion (+/-) which is calculated below.
1160        int Z = X ^ Y;
1161
1162        // extract the axis (remove the sign), offset in the range 0 to 2.
1163        final int x = (X & 0x3)-1;
1164        final int y = (Y & 0x3)-1;
1165        final int z = (Z & 0x3)-1;
1166
1167        // compute the sign of Z (whether it needs to be inverted)
1168        final int axis_y = (z+1)%3;
1169        final int axis_z = (z+2)%3;
1170        if (((x^axis_y)|(y^axis_z)) != 0)
1171            Z ^= 0x80;
1172
1173        final boolean sx = (X>=0x80);
1174        final boolean sy = (Y>=0x80);
1175        final boolean sz = (Z>=0x80);
1176
1177        // Perform R * r, in avoiding actual muls and adds.
1178        final int rowLength = ((length==16)?4:3);
1179        for (int j=0 ; j<3 ; j++) {
1180            final int offset = j*rowLength;
1181            for (int i=0 ; i<3 ; i++) {
1182                if (x==i)   outR[offset+i] = sx ? -inR[offset+0] : inR[offset+0];
1183                if (y==i)   outR[offset+i] = sy ? -inR[offset+1] : inR[offset+1];
1184                if (z==i)   outR[offset+i] = sz ? -inR[offset+2] : inR[offset+2];
1185            }
1186        }
1187        if (length == 16) {
1188            outR[3] = outR[7] = outR[11] = outR[12] = outR[13] = outR[14] = 0;
1189            outR[15] = 1;
1190        }
1191        return true;
1192    }
1193
1194    /**
1195     * Computes the device's orientation based on the rotation matrix.
1196     * <p> When it returns, the array values is filled with the result:
1197     * <li>values[0]: <i>azimuth</i>, rotation around the Z axis.</li>
1198     * <li>values[1]: <i>pitch</i>, rotation around the X axis.</li>
1199     * <li>values[2]: <i>roll</i>, rotation around the Y axis.</li>
1200     * <p>
1201     *
1202     * @param R rotation matrix see {@link #getRotationMatrix}.
1203     * @param values an array of 3 floats to hold the result.
1204     * @return The array values passed as argument.
1205     */
1206    public static float[] getOrientation(float[] R, float values[]) {
1207        /*
1208         * 4x4 (length=16) case:
1209         *   /  R[ 0]   R[ 1]   R[ 2]   0  \
1210         *   |  R[ 4]   R[ 5]   R[ 6]   0  |
1211         *   |  R[ 8]   R[ 9]   R[10]   0  |
1212         *   \      0       0       0   1  /
1213         *
1214         * 3x3 (length=9) case:
1215         *   /  R[ 0]   R[ 1]   R[ 2]  \
1216         *   |  R[ 3]   R[ 4]   R[ 5]  |
1217         *   \  R[ 6]   R[ 7]   R[ 8]  /
1218         *
1219         */
1220        if (R.length == 9) {
1221            values[0] = (float)Math.atan2(R[1], R[4]);
1222            values[1] = (float)Math.asin(-R[7]);
1223            values[2] = (float)Math.atan2(-R[6], R[8]);
1224        } else {
1225            values[0] = (float)Math.atan2(R[1], R[5]);
1226            values[1] = (float)Math.asin(-R[9]);
1227            values[2] = (float)Math.atan2(-R[8], R[10]);
1228        }
1229        return values;
1230    }
1231
1232
1233    /**
1234     * {@hide}
1235     */
1236    public void onRotationChanged(int rotation) {
1237        synchronized(sListeners) {
1238            sRotation  = rotation;
1239        }
1240    }
1241
1242    static int getRotation() {
1243        synchronized(sListeners) {
1244            return sRotation;
1245        }
1246    }
1247
1248    private class LegacyListener implements SensorEventListener {
1249        private float mValues[] = new float[6];
1250        @SuppressWarnings("deprecation")
1251        private SensorListener mTarget;
1252        private int mSensors;
1253        private final LmsFilter mYawfilter = new LmsFilter();
1254
1255        @SuppressWarnings("deprecation")
1256        LegacyListener(SensorListener target) {
1257            mTarget = target;
1258            mSensors = 0;
1259        }
1260
1261        void registerSensor(int legacyType) {
1262            mSensors |= legacyType;
1263        }
1264
1265        boolean unregisterSensor(int legacyType) {
1266            mSensors &= ~legacyType;
1267            int mask = SENSOR_ORIENTATION|SENSOR_ORIENTATION_RAW;
1268            if (((legacyType&mask)!=0) && ((mSensors&mask)!=0)) {
1269                return false;
1270            }
1271            return true;
1272        }
1273
1274        @SuppressWarnings("deprecation")
1275        public void onAccuracyChanged(Sensor sensor, int accuracy) {
1276            try {
1277                mTarget.onAccuracyChanged(sensor.getLegacyType(), accuracy);
1278            } catch (AbstractMethodError e) {
1279                // old app that doesn't implement this method
1280                // just ignore it.
1281            }
1282        }
1283
1284        @SuppressWarnings("deprecation")
1285        public void onSensorChanged(SensorEvent event) {
1286            final float v[] = mValues;
1287            v[0] = event.values[0];
1288            v[1] = event.values[1];
1289            v[2] = event.values[2];
1290            int legacyType = event.sensor.getLegacyType();
1291            mapSensorDataToWindow(legacyType, v, SensorManager.getRotation());
1292            if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
1293                if ((mSensors & SENSOR_ORIENTATION_RAW)!=0) {
1294                    mTarget.onSensorChanged(SENSOR_ORIENTATION_RAW, v);
1295                }
1296                if ((mSensors & SENSOR_ORIENTATION)!=0) {
1297                    v[0] = mYawfilter.filter(event.timestamp, v[0]);
1298                    mTarget.onSensorChanged(SENSOR_ORIENTATION, v);
1299                }
1300            } else {
1301                mTarget.onSensorChanged(legacyType, v);
1302            }
1303        }
1304
1305        /*
1306         * Helper function to convert the specified sensor's data to the windows's
1307         * coordinate space from the device's coordinate space.
1308         *
1309         * output: 3,4,5: values in the old API format
1310         *         0,1,2: transformed values in the old API format
1311         *
1312         */
1313        private void mapSensorDataToWindow(int sensor,
1314                float[] values, int orientation) {
1315            float x = values[0];
1316            float y = values[1];
1317            float z = values[2];
1318
1319            switch (sensor) {
1320                case SensorManager.SENSOR_ORIENTATION:
1321                case SensorManager.SENSOR_ORIENTATION_RAW:
1322                    z = -z;
1323                    break;
1324                case SensorManager.SENSOR_ACCELEROMETER:
1325                    x = -x;
1326                    y = -y;
1327                    z = -z;
1328                    break;
1329                case SensorManager.SENSOR_MAGNETIC_FIELD:
1330                    x = -x;
1331                    y = -y;
1332                    break;
1333            }
1334            values[0] = x;
1335            values[1] = y;
1336            values[2] = z;
1337            values[3] = x;
1338            values[4] = y;
1339            values[5] = z;
1340            // TODO: add support for 180 and 270 orientations
1341            if (orientation == Surface.ROTATION_90) {
1342                switch (sensor) {
1343                    case SENSOR_ACCELEROMETER:
1344                    case SENSOR_MAGNETIC_FIELD:
1345                        values[0] =-y;
1346                        values[1] = x;
1347                        values[2] = z;
1348                        break;
1349                    case SENSOR_ORIENTATION:
1350                    case SENSOR_ORIENTATION_RAW:
1351                        values[0] = x + ((x < 270) ? 90 : -270);
1352                        values[1] = z;
1353                        values[2] = y;
1354                        break;
1355                }
1356            }
1357        }
1358    }
1359
1360    class LmsFilter {
1361        private static final int SENSORS_RATE_MS = 20;
1362        private static final int COUNT = 12;
1363        private static final float PREDICTION_RATIO = 1.0f/3.0f;
1364        private static final float PREDICTION_TIME = (SENSORS_RATE_MS*COUNT/1000.0f)*PREDICTION_RATIO;
1365        private float mV[] = new float[COUNT*2];
1366        private float mT[] = new float[COUNT*2];
1367        private int mIndex;
1368
1369        public LmsFilter() {
1370            mIndex = COUNT;
1371        }
1372
1373        public float filter(long time, float in) {
1374            float v = in;
1375            final float ns = 1.0f / 1000000000.0f;
1376            final float t = time*ns;
1377            float v1 = mV[mIndex];
1378            if ((v-v1) > 180) {
1379                v -= 360;
1380            } else if ((v1-v) > 180) {
1381                v += 360;
1382            }
1383            /* Manage the circular buffer, we write the data twice spaced
1384             * by COUNT values, so that we don't have to copy the array
1385             * when it's full
1386             */
1387            mIndex++;
1388            if (mIndex >= COUNT*2)
1389                mIndex = COUNT;
1390            mV[mIndex] = v;
1391            mT[mIndex] = t;
1392            mV[mIndex-COUNT] = v;
1393            mT[mIndex-COUNT] = t;
1394
1395            float A, B, C, D, E;
1396            float a, b;
1397            int i;
1398
1399            A = B = C = D = E = 0;
1400            for (i=0 ; i<COUNT-1 ; i++) {
1401                final int j = mIndex - 1 - i;
1402                final float Z = mV[j];
1403                final float T = 0.5f*(mT[j] + mT[j+1]) - t;
1404                float dT = mT[j] - mT[j+1];
1405                dT *= dT;
1406                A += Z*dT;
1407                B += T*(T*dT);
1408                C +=   (T*dT);
1409                D += Z*(T*dT);
1410                E += dT;
1411            }
1412            b = (A*B + C*D) / (E*B + C*C);
1413            a = (E*b - A) / C;
1414            float f = b + PREDICTION_TIME*a;
1415
1416            // Normalize
1417            f *= (1.0f / 360.0f);
1418            if (((f>=0)?f:-f) >= 0.5f)
1419                f = f - (float)Math.ceil(f + 0.5f) + 1.0f;
1420            if (f < 0)
1421                f += 1.0f;
1422            f *= 360.0f;
1423            return f;
1424        }
1425    }
1426
1427
1428    private static native void nativeClassInit();
1429
1430    private static native int sensors_module_init();
1431    private static native int sensors_module_get_next_sensor(Sensor sensor, int next);
1432
1433    // Used within this module from outside SensorManager, don't make private
1434    static native int sensors_data_init();
1435    static native int sensors_data_uninit();
1436    static native int sensors_data_open(FileDescriptor fd);
1437    static native int sensors_data_close();
1438    static native int sensors_data_poll(float[] values, int[] status, long[] timestamp);
1439}
1440