Example usage for android.hardware SensorEventListener SensorEventListener

List of usage examples for android.hardware SensorEventListener SensorEventListener

Introduction

In this page you can find the example usage for android.hardware SensorEventListener SensorEventListener.

Prototype

SensorEventListener

Source Link

Usage

From source file:Main.java

public static boolean startHeartMonitor(SensorEventListener listener, int delay) {
    Sensor heartSensor = getSensor(Sensor.TYPE_HEART_RATE);
    if (heartSensor != null) {
        sensorManager.registerListener(new SensorEventListener() {
            @Override/*from  w w  w .j  av a2 s .co m*/
            public void onSensorChanged(SensorEvent event) {

            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {

            }
        }, heartSensor, delay);
    }
    return false;
}

From source file:it.unime.mobility4ckan.MySensor.java

public void registerSensor(Sensor mSensor) {
    LocationListener locationListener = new LocationListener() {
        @Override/*  w  w  w .ja  va2 s .co m*/
        public void onLocationChanged(Location location) {
            //latitude = location.getLatitude();
            //longitude = location.getLongitude();
            currentSpeed = location.getSpeed();
            //locationText.setText(String.valueOf(latitude)+ "  " +String.valueOf(longitude)+ "  " +String.valueOf(speed));
            //isGPSReady = true;
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            //
        }

        @Override
        public void onProviderEnabled(String provider) {
            //
        }

        @Override
        public void onProviderDisabled(String provider) {
            //
        }
    };

    SensorEventListener sensorListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {

            switch (event.sensor.getType()) {
            case Sensor.TYPE_AMBIENT_TEMPERATURE: // Gradi Celsius (C)
                currentTemp = event.values[0];
                break;

            case Sensor.TYPE_PRESSURE:
                currentPressure = event.values[0]; // hPa o mbar
                break;

            case Sensor.TYPE_LIGHT: // lx
                currentLight = event.values[0];
                break;

            case Sensor.TYPE_ACCELEROMETER: // m/s2
                currentAcceleration[0] = event.values[0];
                currentAcceleration[1] = event.values[1];
                currentAcceleration[2] = event.values[2];
                break;

            case Sensor.TYPE_GYROSCOPE: // rad/s
                currentGyroscope[0] = event.values[0];
                currentGyroscope[1] = event.values[1];
                currentGyroscope[2] = event.values[2];
                break;

            case Sensor.TYPE_MAGNETIC_FIELD: // T
                currentMagnetic[0] = event.values[0];
                currentMagnetic[1] = event.values[1];
                currentMagnetic[2] = event.values[2];
                break;

            case Sensor.TYPE_PROXIMITY: // cm
                currentProximity = event.values[0];
                break;

            case Sensor.TYPE_ROTATION_VECTOR: // unita di misura sconosciuta
                currentRotation[0] = event.values[0];
                currentRotation[1] = event.values[1];
                currentRotation[2] = event.values[2];
                break;

            case Sensor.TYPE_GRAVITY: // m/s2
                currentGravity[0] = event.values[0];
                currentGravity[1] = event.values[1];
                currentGravity[2] = event.values[2];
                break;

            case Sensor.TYPE_LINEAR_ACCELERATION: // m/s2
                currentLinearAcceleration[0] = event.values[0];
                currentLinearAcceleration[1] = event.values[1];
                currentLinearAcceleration[2] = event.values[2];
                break;

            case Sensor.TYPE_RELATIVE_HUMIDITY: // %
                currentHumidity = event.values[0];
                break;

            default:
                break;
            }

        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    //sensorManager.registerListener(locationListener, mSensor, LocationManager.GPS_PROVIDER);
    /*        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    // TODO: Consider calling
    //    ActivityCompat#requestPermissions
    // here to request the missing permissions, and then overriding
    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
    //                                          int[] grantResults)
    // to handle the case where the user grants the permission. See the documentation
    // for ActivityCompat#requestPermissions for more details.
    return;
            }*/
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    sensorManager.registerListener(sensorListener, mSensor, SensorManager.SENSOR_DELAY_FASTEST);
}

From source file:it.cnr.isti.doremi.sleeplogger.SensorSamplingService.java

@Override
public void onCreate() {
    super.onCreate();
    Log.i(TAG, "onCreate()");

    mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));

    /*for (Sensor s : mSensorManager.getSensorList(Sensor.TYPE_ALL)) // print all the available sensors
    {/*w  w  w . j  a v  a 2s .co m*/
       Log.d(TAG, "Sensor: " + s.getName() + ", type = " + s.getType());
    }*/

    // Use SENSOR_TYPE_HEARTRATE_GEAR_LIVE below to have a better accuracy (only for Samsung Gear Live)
    mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
    selHB = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            lastHB = sensorEvent.values[0];
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {
        }
    };
    mSensorManager.registerListener(selHB, this.mHeartRateSensor, 500000); // Forced to 0.5s

    mAccelerationSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    selAcc = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            lastAcc = sensorEvent.values;
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {
        }
    };
    mSensorManager.registerListener(selAcc, this.mAccelerationSensor, SAMPLING_INTERVAL * 750); // sampling interval * 0.75

    // ENABLE IF REQUIRED
    /*      mGyroscopeSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
          selGyroscope = new SensorEventListener() {
             @Override
             public void onSensorChanged(SensorEvent sensorEvent) { lastGyro = sensorEvent.values; }
            
             @Override
             public void onAccuracyChanged(Sensor sensor, int i) {}
          };
          mSensorManager.registerListener(selGyroscope, this.mGyroscopeSensor, SAMPLING_INTERVAL * 1000);
            
          mOrientationSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
          selOrientation = new SensorEventListener() {
             @Override
             public void onSensorChanged(SensorEvent sensorEvent) { lastOrientation = sensorEvent.values; }
            
             @Override
             public void onAccuracyChanged(Sensor sensor, int i) {}
          };
          mSensorManager.registerListener(selOrientation, this.mOrientationSensor, SAMPLING_INTERVAL * 1000);
            
          mStepSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
          selStep = new SensorEventListener() {
             @Override
             public void onSensorChanged(SensorEvent sensorEvent) { lastStepCount = sensorEvent.values[0]; }
            
             @Override
             public void onAccuracyChanged(Sensor sensor, int i) {}
          };
          mSensorManager.registerListener(selStep, this.mStepSensor, 1000000); // Forced to 1s
    */
    File logFile = new File(Environment.getExternalStorageDirectory() + File.separator + "logs" + File.separator
            + "hb_log-" + sdf.format(new Date()) + ".txt");
    try {
        logFile.getParentFile().mkdirs();
        logFile.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    try {
        Log.d(TAG, "Log saved to : " + logFile.getAbsolutePath());
        bw = new BufferedWriter(new FileWriter(logFile));
        bw.write(String.format(Locale.ENGLISH, LOG_HEADER));
    } catch (Exception e) {
        e.printStackTrace();
    }

    powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SensorSamplingServiceWakeLock");
}

From source file:com.microsoft.mimickeralarm.mimics.MimicWithCameraFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_camera_mimic, container, false);

    SurfaceView previewView = (SurfaceView) view.findViewById(R.id.camera_preview_view);

    Display display = getActivity().getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);/*from  w  ww  . ja  v  a2 s.  co  m*/
    mSize = size;
    double aspectRatio = size.y > size.x ? (double) size.y / (double) size.x
            : (double) size.x / (double) size.y;
    mCameraPreview = new CameraPreview(previewView, aspectRatio, CameraFacing);

    View overlay = view.findViewById(R.id.camera_preview_overlay);
    overlay.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                // Camera sensor ranges from -1000 to 1000 regardless of aspect ratio, sizes, resolution, ...
                int deltaX = (int) (((float) mSize.x - event.getX()) / mSize.x * -2000) + 1000;
                int deltaY = (int) (((float) mSize.y - event.getY()) / mSize.y * -2000) + 1000;
                mCameraPreview.onFocus(deltaX, deltaY);
            }
            return true;
        }
    });

    ProgressButton progressButton = (ProgressButton) view.findViewById(R.id.capture_button);
    progressButton.setReadyState(ProgressButton.State.ReadyCamera);

    mStateManager = new MimicStateManager();
    mStateManager.registerCountDownTimer((CountDownTimerView) view.findViewById(R.id.countdown_timer),
            TIMEOUT_MILLISECONDS);
    mStateManager.registerStateBanner((MimicStateBanner) view.findViewById(R.id.mimic_state));
    mStateManager.registerProgressButton(progressButton, MimicButtonBehavior.CAMERA);
    mStateManager.registerMimic(this);

    mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    if (mSensorManager != null) {
        mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    }
    mLightSensorListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.values[0] < LIGHT_THRESHOLD && CameraFacing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                mTooDarkToast.show();
            } else {
                mTooDarkToast.cancel();
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };
    // This toast is only shown when there is not enough light
    mTooDarkToast = Toast.makeText(getActivity(), getString(R.string.mimic_camera_too_dark),
            Toast.LENGTH_SHORT);

    return view;
}

From source file:com.example.haber.ui.activity.TabbedActivity.java

@Override
protected void onResume() {
    super.onResume();
    lastTime = System.currentTimeMillis();
    try {// w w  w.  java2 s.c  om
        sensorListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                try {
                    long currentTime = System.currentTimeMillis();
                    long intevalTime = currentTime - lastTime;
                    if (intevalTime < 50)
                        return;
                    lastTime = currentTime;
                    float[] values = event.values;
                    float x = values[0];
                    float y = values[1];
                    float z = values[2];
                    float detaX = x - lastX;
                    float detaY = y - lastY;
                    float detaZ = z - lastZ;
                    lastX = x;
                    lastY = y;
                    lastZ = z;
                    if ((Math.sqrt(detaX * detaX + detaY * detaY + detaZ * detaZ) / intevalTime)
                            * 100 < SENSOR_SENSITIVITY)
                        return;
                    if (vibrator == null)
                        return;
                    vibrator.vibrate(300);
                    long currentSwitchPanTime = System.currentTimeMillis();
                    if (currentSwitchPanTime - lastSwichPanTime < 1000)
                        return;
                    lastSwichPanTime = currentSwitchPanTime;
                    switchPan();
                } catch (Exception e) {
                    ExceptionUtil.handlerException(e);
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {

            }
        };
        if (currentStatus == CONSOLE_CONTROL_STATUS) {
            if (sensor == null)
                return;
            sensorManager.registerListener(sensorListener, sensor, SensorManager.SENSOR_DELAY_UI);
        }

        handlerCallStatus();
    } catch (Exception e) {
        ExceptionUtil.handlerException(e);
    }

}

From source file:it.unime.mobility4ckan.MySensor.java

void registerTempSensor() {
    tempSensorListener = new SensorEventListener() {
        @Override//from  w  w  w .j  av a 2 s.c  om
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE)
                currentTemp = event.values[0];
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    sensorManager.registerListener(tempSensorListener, tempSensor, SensorManager.SENSOR_DELAY_FASTEST);
}

From source file:it.unime.mobility4ckan.MySensor.java

void registerPressureSensor() {
    pressureSensorListener = new SensorEventListener() {
        @Override//  w w w  .j av  a2s  . co  m
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() == Sensor.TYPE_PRESSURE) {
                currentPressure = event.values[0];
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    sensorManager.registerListener(pressureSensorListener, pressureSensor, SensorManager.SENSOR_DELAY_FASTEST);
}

From source file:it.unime.mobility4ckan.MySensor.java

void registerLightSensor() {
    lightSensorListener = new SensorEventListener() {
        @Override//from  w  w  w. j av  a 2  s  .com
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
                currentLight = event.values[0];
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    sensorManager.registerListener(lightSensorListener, lightSensor, SensorManager.SENSOR_DELAY_FASTEST);
}

From source file:tv.piratemedia.flightcontroller.BluetoothComputerFragment.java

public void setupAtimiter() {
    SensorManager mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    List<Sensor> sensors = mSensorManager.getSensorList(Sensor.TYPE_PRESSURE);
    SensorEventListener sensorListener = new SensorEventListener() {
        @Override/*from w w w .  j ava  2 s  . c  o m*/
        public void onSensorChanged(SensorEvent event) {
            if (currentPreasure > event.values[0] - 0.5 || currentPreasure < event.values[0] + 0.5) {
                currentPreasure = event.values[0];
                currentAltitude = SensorManager.getAltitude(SensorManager.PRESSURE_STANDARD_ATMOSPHERE,
                        currentPreasure);

                JSONObject msg = new JSONObject();
                try {
                    msg.put("action", "altitude_update");
                    msg.put("value", currentAltitude);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sendTextMessage(msg.toString());
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };
    if (sensors.size() > 0) {
        sensor = sensors.get(0);
        mSensorManager.registerListener(sensorListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    } else {

    }
}

From source file:tv.piratemedia.flightcontroller.BluetoothComputerFragment.java

public void setupAccel() {
    SensorManager mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    Sensor mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);

    mSensorManager.registerListener(new SensorEventListener() {
        @Override//from w  ww .  jav a 2 s . com
        public void onSensorChanged(SensorEvent event) {
            if (!Moving && currentTrottle > 20) {
                float[] filtered = new float[3];
                lowPass(event.values, filtered);

                float x = getAverageX(filtered[0]);
                float y = getAverageY(filtered[1]);

                currentXOffset += x * multiValue;
                currentYOffset += y * multiValue;

                if (currentXOffset > maxOffset) {
                    currentXOffset = maxOffset;
                } else if (currentXOffset < -maxOffset) {
                    currentXOffset = -maxOffset;
                }

                if (currentYOffset > maxOffset) {
                    currentYOffset = maxOffset;
                } else if (currentYOffset < -maxOffset) {
                    currentYOffset = -maxOffset;
                }

                if (PitchCorrection != (int) currentYOffset && RollCorrection != (int) currentXOffset) {
                    PitchCorrection = (int) currentYOffset;
                    RollCorrection = -(int) currentXOffset;

                    JSONObject msg = new JSONObject();
                    try {
                        msg.put("action", "correction_update");
                        msg.put("pitch", PitchCorrection);
                        msg.put("roll", RollCorrection);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    sendTextMessage(msg.toString());
                    updateThrottle(currentTrottle);
                }
            } else if (!Moving && currentTrottle <= 20) {
                PitchCorrection = 0;
                RollCorrection = 0;

                JSONObject msg = new JSONObject();
                try {
                    msg.put("action", "correction_update");
                    msg.put("pitch", PitchCorrection);
                    msg.put("roll", RollCorrection);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sendTextMessage(msg.toString());
                updateThrottle(currentTrottle);
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    }, mSensor, SensorManager.SENSOR_DELAY_FASTEST);
}