1 package org.robolectric.shadows; 2 3 import static org.robolectric.util.reflector.Reflector.reflector; 4 5 import android.hardware.Sensor; 6 import android.os.Build.VERSION_CODES; 7 import org.robolectric.RuntimeEnvironment; 8 import org.robolectric.annotation.Implementation; 9 import org.robolectric.annotation.Implements; 10 import org.robolectric.annotation.RealObject; 11 import org.robolectric.shadow.api.Shadow; 12 import org.robolectric.util.reflector.Accessor; 13 import org.robolectric.util.reflector.ForType; 14 import org.robolectric.util.reflector.Static; 15 16 @Implements(Sensor.class) 17 public class ShadowSensor { 18 19 @RealObject private Sensor realSensor; 20 21 private float maximumRange = 0; 22 23 /** Constructs a {@link Sensor} with a given type. */ newInstance(int type)24 public static Sensor newInstance(int type) { 25 Sensor sensor = Shadow.newInstanceOf(Sensor.class); 26 reflector(_Sensor_.class, sensor).setTypeCompat(type); 27 return sensor; 28 } 29 30 /** Controls the return value of {@link Sensor#isWakeUpSensor()}. */ setWakeUpFlag(boolean wakeup)31 public void setWakeUpFlag(boolean wakeup) { 32 int wakeUpSensorMask = reflector(_Sensor_.class).getWakeUpSensorFlag(); 33 34 if (wakeup) { 35 setMask(wakeUpSensorMask); 36 } else { 37 clearMask(wakeUpSensorMask); 38 } 39 } 40 41 /** Sets the return value for {@link Sensor#getMaximumRange}. */ setMaximumRange(float range)42 public void setMaximumRange(float range) { 43 maximumRange = range; 44 } 45 46 @Implementation getMaximumRange()47 protected float getMaximumRange() { 48 return maximumRange; 49 } 50 51 /** Sets the return value for {@link Sensor#getMinDelay}. */ setMinDelay(int delay)52 public void setMinDelay(int delay) { 53 reflector(_Sensor_.class, realSensor).setMinDelay(delay); 54 } 55 setMask(int mask)56 private void setMask(int mask) { 57 _Sensor_ _sensor_ = reflector(_Sensor_.class, realSensor); 58 _sensor_.setFlags(_sensor_.getFlags() | mask); 59 } 60 clearMask(int mask)61 private void clearMask(int mask) { 62 _Sensor_ _sensor_ = reflector(_Sensor_.class, realSensor); 63 _sensor_.setFlags(_sensor_.getFlags() & ~mask); 64 } 65 66 /** Accessor interface for {@link Sensor}'s internals. */ 67 @ForType(Sensor.class) 68 interface _Sensor_ { 69 70 @Accessor("mType") setTypeField(int type)71 void setTypeField(int type); 72 setType(int type)73 void setType(int type); 74 setTypeCompat(int type)75 default void setTypeCompat(int type) { 76 if (RuntimeEnvironment.getApiLevel() >= VERSION_CODES.M) { 77 setType(type); 78 } else { 79 setTypeField(type); 80 } 81 } 82 83 @Accessor("mFlags") getFlags()84 int getFlags(); 85 86 @Accessor("mFlags") setFlags(int flags)87 void setFlags(int flags); 88 89 @Accessor("mMinDelay") setMinDelay(int minDelay)90 void setMinDelay(int minDelay); 91 92 @Static 93 @Accessor("SENSOR_FLAG_WAKE_UP_SENSOR") getWakeUpSensorFlag()94 int getWakeUpSensorFlag(); 95 } 96 } 97