1 package org.robolectric.shadows;
2 
3 import static com.google.common.base.Preconditions.checkArgument;
4 
5 import android.annotation.NonNull;
6 import android.hardware.Sensor;
7 import android.hardware.SensorEvent;
8 import org.robolectric.util.ReflectionHelpers;
9 import org.robolectric.util.ReflectionHelpers.ClassParameter;
10 
11 /** Builder for {@link SensorEvent}. */
12 public class SensorEventBuilder {
13   private float[] values;
14   private int accuracy = 0;
15   private long timestampNs = 0;
16   private Sensor sourceSensor = null;
17 
SensorEventBuilder()18   private SensorEventBuilder() {}
19 
newBuilder()20   public static SensorEventBuilder newBuilder() {
21     return new SensorEventBuilder();
22   }
23 
setValues(@onNull float[] value)24   public SensorEventBuilder setValues(@NonNull float[] value) {
25     values = value;
26     return this;
27   }
28 
29   /**
30    * If the 'type' property of Sensor is all that is important to your use case, an instance of from
31    * ShadowSensor.newInstance(sensorType) should suffice.
32    */
setSensor(@onNull Sensor value)33   public SensorEventBuilder setSensor(@NonNull Sensor value) {
34     sourceSensor = value;
35     return this;
36   }
37 
setTimestamp(long value)38   public SensorEventBuilder setTimestamp(long value) {
39     timestampNs = value;
40     return this;
41   }
42 
setAccuracy(int value)43   public SensorEventBuilder setAccuracy(int value) {
44     accuracy = value;
45     return this;
46   }
47 
build()48   public SensorEvent build() {
49     // SensorEvent values and a source Sensor object need be set.
50     checkArgument(values != null && values.length > 0);
51     checkArgument(sourceSensor != null);
52 
53     SensorEvent sensorEvent =
54         ReflectionHelpers.callConstructor(
55             SensorEvent.class, ClassParameter.from(int.class, values.length));
56 
57     System.arraycopy(values, 0, sensorEvent.values, 0, values.length);
58     sensorEvent.accuracy = accuracy;
59     sensorEvent.timestamp = timestampNs;
60     sensorEvent.sensor = sourceSensor;
61 
62     return sensorEvent;
63   }
64 }
65