android.hardware.Sensor Java Examples

The following examples show how to use android.hardware.Sensor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StepCounterService.java    From BackPackTrackII with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.edit().remove(SettingsFragment.PREF_LAST_STEP_COUNT).apply();

    SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    Sensor stepCounter = sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
    if (stepCounter == null)
        Log.w(TAG, "No hardware stepcounter available");
    else {
        Log.w(TAG, "Registering step counter listener");
        sm.registerListener(mStepCounterListener, stepCounter, SensorManager.SENSOR_DELAY_NORMAL);
    }
}
 
Example #2
Source File: Tsl256xSensorDriver.java    From androidthings-drivers with Apache License 2.0 6 votes vote down vote up
private UserSensor getUserSensor() {
    if (mUserSensor == null) {
        mUserSensor = new UserSensor.Builder()
                .setType(Sensor.TYPE_LIGHT)
                .setName(DRIVER_NAME)
                .setVendor(DRIVER_VENDOR)
                .setVersion(DRIVER_VERSION)
                .setMaxRange(DRIVER_MAX_RANGE)
                .setPower(DRIVER_POWER)
                .setMinDelay(DRIVER_XG_MIN_DELAY_US)
                .setMaxDelay(DRIVER_XG_MAX_DELAY_US)
                .setUuid(UUID.randomUUID())
                .setDriver(this)
                .build();
    }
    return mUserSensor;
}
 
Example #3
Source File: SensorTestActivity.java    From codeexamples-android with Eclipse Public License 1.0 6 votes vote down vote up
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
			WindowManager.LayoutParams.FLAG_FULLSCREEN);

	setContentView(R.layout.main);
	view = findViewById(R.id.textView);
	view.setBackgroundColor(Color.GREEN);

	sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
	sensorManager.registerListener(this,
			sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
			SensorManager.SENSOR_DELAY_NORMAL);
	lastUpdate = System.currentTimeMillis();
}
 
Example #4
Source File: AlternativeAccelHandler.java    From Alite with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
	if (!getUpdates) {
		SensorManager manager = (SensorManager) game.getSystemService(Context.SENSOR_SERVICE);
		if (manager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() > 0) {
			manager.unregisterListener(this);
		}			
		return;
	}
	switch (event.sensor.getType()) {
		case Sensor.TYPE_ACCELEROMETER:
			for (int i = 0; i < 3; i++) {
				accelValues[i] = event.values[i];
			}
			break;
	}

	float roll  = (float) Math.atan2(accelValues[0], accelValues[2]);
	float pitch = (float) Math.atan2(accelValues[1], accelValues[2]);

	accelValues[2] = -roll;
	accelValues[1] = -pitch;
	accelValues[0] = 0;
	adjustAccelOrientation(accelValues);
}
 
Example #5
Source File: ControllerActivity.java    From Bluefruit_LE_Connect_Android with MIT License 6 votes vote down vote up
@Override
public final void onSensorChanged(SensorEvent event) {
    int sensorType = event.sensor.getType();
    if (sensorType == Sensor.TYPE_ACCELEROMETER) {
        mSensorData[kSensorType_Accelerometer].values = event.values;

        updateOrientation();            // orientation depends on Accelerometer and Magnetometer
        mControllerListAdapter.notifyDataSetChanged();
    } else if (sensorType == Sensor.TYPE_GYROSCOPE) {
        mSensorData[kSensorType_Gyroscope].values = event.values;

        mControllerListAdapter.notifyDataSetChanged();
    } else if (sensorType == Sensor.TYPE_MAGNETIC_FIELD) {
        mSensorData[kSensorType_Magnetometer].values = event.values;

        updateOrientation();            // orientation depends on Accelerometer and Magnetometer
        mControllerListAdapter.notifyDataSetChanged();
    }
}
 
Example #6
Source File: WeatherStationActivity.java    From androidthings-weatherstation with Apache License 2.0 6 votes vote down vote up
@Override
protected void onStart() {
    super.onStart();

    // Register the BMP280 temperature sensor
    Sensor temperature = mSensorManager
            .getDynamicSensorList(Sensor.TYPE_AMBIENT_TEMPERATURE).get(0);
    mSensorManager.registerListener(mSensorEventListener, temperature,
            SensorManager.SENSOR_DELAY_NORMAL);

    // Register the BMP280 pressure sensor
    Sensor pressure = mSensorManager
            .getDynamicSensorList(Sensor.TYPE_PRESSURE).get(0);
    mSensorManager.registerListener(mSensorEventListener, pressure,
            SensorManager.SENSOR_DELAY_NORMAL);
}
 
Example #7
Source File: MeiFireflyActivity.java    From kAndroid with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mei_firefly);
    mMobikeView = findViewById(R.id.mo_bike);

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

    addViews();

    mMobikeView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mMobikeView.onRandomChanged();
        }
    });
}
 
Example #8
Source File: SensorMetricsCollectorTest.java    From Battery-Metrics with MIT License 5 votes vote down vote up
/**
 *
 *
 * <pre>
 * Time                = 01 .. 10 .. 15 .. 20 .. 50
 * Sensor A/Listener A = [............]
 * Sensor B/Listener B =       [............]
 * </pre>
 */
@Test
public void test_attribution_snapshot() {
  Sensor sensorB = mock(Sensor.class);
  SensorEventListener listenerB = mock(SensorEventListener.class);

  when(sensorB.getType()).thenReturn(2);
  when(sensorB.getPower()).thenReturn(100.0f);

  ShadowSystemClock.setElapsedRealtime(1);
  collector.register(listener, sensor);

  ShadowSystemClock.setElapsedRealtime(10);
  collector.register(listenerB, sensorB);

  ShadowSystemClock.setElapsedRealtime(15);
  collector.unregister(listener, null);

  ShadowSystemClock.setElapsedRealtime(20);
  collector.unregister(listenerB, null);

  ShadowSystemClock.setElapsedRealtime(50);

  metrics.isAttributionEnabled = true;
  assertThat(collector.getSnapshot(metrics)).isTrue();
  assertThat(metrics.total.activeTimeMs).isEqualTo(14 + 10);
  assertThat(metrics.sensorConsumption.size()).isEqualTo(2);
  assertThat(metrics.sensorConsumption.get(1337).activeTimeMs).isEqualTo(14);
  assertThat(metrics.sensorConsumption.get(1337).powerMah)
      .isEqualTo((14.0 * (double) sensor.getPower()) / 3600 / 1000);
  assertThat(metrics.sensorConsumption.get(2).activeTimeMs).isEqualTo(10);
  assertThat(metrics.sensorConsumption.get(2).powerMah)
      .isEqualTo((10.0 * (double) sensorB.getPower()) / 3600 / 1000);
}
 
Example #9
Source File: CustomShakeDetector.java    From react-native-shake with MIT License 5 votes vote down vote up
/**
 * Start listening for shakes.
 */
public void start(SensorManager manager) {
  Assertions.assertNotNull(manager);
  Sensor accelerometer = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
  if (accelerometer != null) {
    mSensorManager = manager;
    mLastTimestamp = -1;
    mCurrentIndex = 0;
    mMagnitudes = new double[MAX_SAMPLES];
    mTimestamps = new long[MAX_SAMPLES];
    mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
    mNumShakes = 0;
    mLastShakeTimestamp = 0;
  }
}
 
Example #10
Source File: Compass.java    From SensorsAndAi with MIT License 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent sensorEvent) {

    final  float alpha= 0.97f;
    synchronized (this){
        if (sensorEvent.sensor.getType ()==Sensor.TYPE_ACCELEROMETER){
            mGravity[0]= alpha*mGravity[0]+(1-alpha)*sensorEvent.values[0];
            mGravity[1]= alpha*mGravity[1]+(1-alpha)*sensorEvent.values[1];
            mGravity[2]= alpha*mGravity[2]+(1-alpha)*sensorEvent.values[2];
        }

        if (sensorEvent.sensor.getType ()==Sensor.TYPE_MAGNETIC_FIELD){
            mGeomagnetic[0]= alpha*mGeomagnetic[0]+(1-alpha)*sensorEvent.values[0];
            mGeomagnetic[1]= alpha*mGeomagnetic[1]+(1-alpha)*sensorEvent.values[1];
            mGeomagnetic[2]= alpha*mGeomagnetic[2]+(1-alpha)*sensorEvent.values[2];
        }
        float R[] =new  float[9];
        float I[] =new  float[9];
        boolean success = SensorManager.getRotationMatrix ( R,I,mGravity,mGeomagnetic );
        if (success) {
            float orientation[] = new float[3];
            SensorManager.getOrientation ( R,orientation );
            azimuth =(float)Math.toDegrees ( orientation[0] );
            azimuth = (azimuth+360)%360;
            //
            Animation anim =new RotateAnimation ( -correctAzimuth,-azimuth, Animation.RELATIVE_TO_SELF,0.5f
                    ,Animation.RELATIVE_TO_SELF,0.5f);
            correctAzimuth = azimuth;
            anim.setDuration ( 500 );
            anim.setRepeatCount ( 0 );
            anim.setFillAfter ( true );

            imageView.startAnimation ( anim );
        }
    }

}
 
Example #11
Source File: CameraActivity.java    From camerademo with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
        //光线强度
        float lux = event.values[0];
        Log.e(TAG, "光线传感器得到的光线强度-->" + lux);
    }
}
 
Example #12
Source File: AmbientLightManager.java    From ZXing-Orient with Apache License 2.0 5 votes vote down vote up
void start(CameraManager cameraManager) {
  this.cameraManager = cameraManager;
  SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
  if (FrontLightMode.readPref(sharedPrefs) == FrontLightMode.AUTO) {
    SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
    lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    if (lightSensor != null) {
      sensorManager.registerListener(this, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }
  }
}
 
Example #13
Source File: EmulatorCheckUtil.java    From EasyProtector with Apache License 2.0 5 votes vote down vote up
/**
 * 判断是否存在光传感器来判断是否为模拟器
 * 部分真机也不存在温度和压力传感器。其余传感器模拟器也存在。
 *
 * @return false为模拟器
 */
private boolean hasLightSensor(Context context) {
    SensorManager sensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);
    Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); //光线传感器
    if (null == sensor) return false;
    else return true;
}
 
Example #14
Source File: SensorEventsController.java    From applivery-android-sdk with Apache License 2.0 5 votes vote down vote up
private void sensorAction(int action, AndroidSensorWrapper androidSensorWrapper) {
  SensorEventListener sensorEventListener = androidSensorWrapper.getSensorEventListener();
  Sensor sensor = sensorManager.getDefaultSensor(androidSensorWrapper.getAndroidSensorType());
  //if (action == REGISTER && androidSensorWrapper.isEnabled()){
  if (action == REGISTER){
    sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    androidSensorWrapper.setRegistered(true);
  }else if (action == UNREGISTER){
    //}else if (action == UNREGISTER
    //    && androidSensorWrapper.isEnabled() && androidSensorWrapper.isRegistered()){
    sensorManager.unregisterListener(sensorEventListener, sensor);
    androidSensorWrapper.setRegistered(false);
  }
}
 
Example #15
Source File: Reminders.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
        proximity_events++;
        if (proximity_events < 20)
            Log.d(TAG, "Sensor: " + event.values[0] + " " + mProximity.getMaximumRange());
        if (event.values[0] <= (Math.min(mProximity.getMaximumRange() / 2, 10))) {
            proximity = true; // near
        } else {
            proximity = false; // far
        }
        if (proximity_events < 20) Log.d(TAG, "Proxmity set to: " + proximity);
    }
}
 
Example #16
Source File: MainActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 5 votes vote down vote up
public void onSensorChanged(SensorEvent sensorEvent) {
  if (sensorEvent.sensor.getType() == Sensor.TYPE_HEART_RATE) {
    if (sensorEvent.accuracy == SensorManager.SENSOR_STATUS_NO_CONTACT ||
          sensorEvent.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) {
      Log.d(TAG, "Heart Rate Monitor not in contact or unreliable");
    } else {
      float currentHeartRate = sensorEvent.values[0];
      Log.d(TAG, "Heart Rate: " + currentHeartRate);
    }
  }
}
 
Example #17
Source File: DiagnosticsActivity.java    From osmdroid with Apache License 2.0 5 votes vote down vote up
private void probeOrientation() {
    StringBuilder sb = new StringBuilder();
    SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    List<Sensor> sensorList = mSensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
    for (Sensor s : sensorList) {

        sb.append(s.getName() + ":" + s.toString() + "\n");
    }
    output.setText(sb.toString());
}
 
Example #18
Source File: SensorListener.java    From Telephoto with Apache License 2.0 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        float xy_angle = event.values[0]; //Плоскость XY
        float xz_angle = event.values[1]; //Плоскость XZ
        float zy_angle = event.values[2]; //Плоскость ZY

        float sum = (xy_angle + xz_angle + zy_angle);

        if (mPosition == 0) {
            mPosition = sum;
        }
        float vibrationLevel = Math.abs(mPosition - sum);
        if (vibrationLevel > 0.5) {
            L.d("Diff: " + vibrationLevel);
        }
        if (vibrationLevel > type.getShakeValue()) {
            L.i("Shake detected! Diff: " + vibrationLevel);
            long time = System.currentTimeMillis();
            if (alarmTime == 0 || (time - alarmTime) > TIMEOUT) {
                if (service != null) {
                    service.sendMessageToAll(context.getString(R.string.alarm_shake));
                }
                alarmTime = time;
            }
        }
        mPosition = sum;
    } else {
        L.i(String.format("eventName: %s, eventType: %s", event.sensor.getName(), event.sensor.getType()));
        for (int i = 0; i < event.values.length; i++) {
            L.i(String.format("value %s: %s", i, event.values[i]));
        }
    }
}
 
Example #19
Source File: AndroidSensorJoyInput.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Pauses the sensors to save battery life if the sensors are not needed.
 * Used to pause sensors when the activity pauses
 */
public void pauseSensors() {
    for (Entry entry: sensors) {
        if (entry.getKey() != Sensor.TYPE_ORIENTATION) {
            unRegisterListener(entry.getKey());
        }
    }
}
 
Example #20
Source File: PLView.java    From PanoramaGL with Apache License 2.0 5 votes vote down vote up
/**accelerometer methods*/
   
protected boolean activateAccelerometer()
{
	if(mSensorManager != null && mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), (int)(mAccelerometerInterval * 1000.0f)))
		return true;
	PLLog.debug("PLView::activateAccelerometer", "Accelerometer sensor is not available on the device!");
	return false;
}
 
Example #21
Source File: MainActivity.java    From journaldev with MIT License 5 votes vote down vote up
public void stepCounterOnClick(View view) {
    if (checkSensorAvailability(Sensor.TYPE_STEP_DETECTOR)) {
        currentSensor = Sensor.TYPE_STEP_DETECTOR;
    } else {
        textView.setText("Step Counter Sensor not available");
    }
}
 
Example #22
Source File: ProximityService.java    From CoolClock with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    Sensor mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    mSensorManager.registerListener(mSensorListener, mSensor, SensorManager.SENSOR_DELAY_FASTEST);

}
 
Example #23
Source File: Drawer.java    From meter with Apache License 2.0 5 votes vote down vote up
public void start(){

        mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

        mLastAccelerometerSet = false;
        mLastMagnetometerSet = false;
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_NORMAL);

    }
 
Example #24
Source File: GPSSensorEventListenerTest.java    From JayPS-AndroidApp with MIT License 5 votes vote down vote up
@SmallTest
public void testWhenOnAltitudeChangedWithSoemthingOtherThanPressureDoesNotCallCallback() throws InterruptedException {
    float[] data = new float[] {1.0f};
    _listener.sensorChanged(Sensor.TYPE_ACCELEROMETER, data);

    _latch.await(2000, TimeUnit.MILLISECONDS);
    assertEquals(1,_latch.getCount());
}
 
Example #25
Source File: SensorActivityTest.java    From AndPermission with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test() throws Throwable {
    SensorManager sensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
    try {
        Sensor heartRateSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
        sensorManager.registerListener(SENSOR_EVENT_LISTENER, heartRateSensor, 3);
        sensorManager.unregisterListener(SENSOR_EVENT_LISTENER, heartRateSensor);
    } catch (Throwable e) {
        PackageManager packageManager = mContext.getPackageManager();
        return !packageManager.hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_DETECTOR);
    }
    return true;
}
 
Example #26
Source File: AccelerometerHandler.java    From Alite with GNU General Public License v3.0 5 votes vote down vote up
public AccelerometerHandler(AndroidGame game) {
	this.game = game;
	defaultOrientation = getDeviceDefaultOrientation();		
	deviceOrientationManager = new DeviceOrientationManager();
	SensorManager manager = (SensorManager) game.getSystemService(Context.SENSOR_SERVICE);
	if (manager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() > 0) {
		Sensor accelerometer = manager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
		manager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
		getUpdates = true;
	} 
	deviceOrientationManager.enable();
}
 
Example #27
Source File: AccelerometerManager.java    From SensorAnnotations with Apache License 2.0 4 votes vote down vote up
@OnSensorNotAvailable(Sensor.TYPE_ACCELEROMETER)
void testTemperatureSensorNotAvailable() {
    mMainActivity.updateTextViewWithSensorNotAvailable(mAccelerometerManagerTextView);
}
 
Example #28
Source File: CompassTile.java    From GravityBox with Apache License 2.0 4 votes vote down vote up
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // noop
}
 
Example #29
Source File: SensorEventListenerProxy.java    From osmdroid with Apache License 2.0 4 votes vote down vote up
@Override
public void onAccuracyChanged(final Sensor pSensor, final int pAccuracy) {
	if (mListener != null) {
		mListener.onAccuracyChanged(pSensor, pAccuracy);
	}
}
 
Example #30
Source File: KaabaLocatorFragment.java    From PrayTime-Android with Apache License 2.0 4 votes vote down vote up
private void registerRotationListener() {
  if (mMap != null && mLastLocation != null && !mRegistered) {
    mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), SensorManager.SENSOR_DELAY_UI);
    mRegistered = true;
  }
}