aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/sensors/OrientationProvider.java
blob: ce84ffbb6c94a1ed62541fbbc40228e6ed34b37e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package cgeo.geocaching.sensors;

import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.RxUtils.LooperCallbacks;

import rx.Observable;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class OrientationProvider extends LooperCallbacks<Float> implements SensorEventListener {

    private final SensorManager sensorManager;
    private final Sensor orientationSensor;

    @SuppressWarnings("deprecation")
    protected OrientationProvider(final Context context) {
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        orientationSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        if (orientationSensor != null) {
            Log.d("OrientationProvider: sensor found");
        } else {
            Log.w("OrientationProvider: no orientation sensor on this device");
        }
    }

    @SuppressWarnings("deprecation")
    public static boolean hasOrientationSensor(final Context context) {
        return ((SensorManager) context.getSystemService(Context.SENSOR_SERVICE)).getDefaultSensor(Sensor.TYPE_ORIENTATION) != null;
    }

    @Override
    public void onSensorChanged(final SensorEvent event) {
            subject.onNext(event.values[0]);
    }

    @Override
    public void onAccuracyChanged(final Sensor sensor, final int accuracy) {
        /*
         * There is a bug in Android, which apparently causes this method to be called every
         * time the sensor _value_ changed, even if the _accuracy_ did not change. Do not have any code in here.
         *
         * See for example https://code.google.com/p/android/issues/detail?id=14792
         */
    }

    @Override
    public void onStart() {
        if (orientationSensor != null) {
            Log.d("OrientationProvider: starting the orientation provider");
            sensorManager.registerListener(this, orientationSensor, SensorManager.SENSOR_DELAY_NORMAL);
        } else {
            subject.onError(new RuntimeException("orientation sensor is absent on this device"));
        }
    }

    @Override
    public void onStop() {
        if (orientationSensor != null) {
            Log.d("OrientationProvider: stopping the orientation provider");
            sensorManager.unregisterListener(this);
        }
    }

    public static Observable<Float> create(final Context context) {
        return Observable.create(new OrientationProvider(context)).onBackpressureDrop();
    }

}