Example usage for android.hardware Sensor TYPE_ACCELEROMETER

List of usage examples for android.hardware Sensor TYPE_ACCELEROMETER

Introduction

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

Prototype

int TYPE_ACCELEROMETER

To view the source code for android.hardware Sensor TYPE_ACCELEROMETER.

Click Source Link

Document

A constant describing an accelerometer sensor type.

Usage

From source file:de.uni_weimar.benike.misex3.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // register for accelerometer events:
    mSensorManager = (SensorManager) getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
    for (Sensor sensor : mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER)) {
        if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            mAccelerometerSensor = sensor;
        }//from w w  w  .  j ava2 s . c  o m
    }

    // if we can't access the accelerometer sensor then exit:
    if (mAccelerometerSensor == null) {
        Log.e(TAG, "Failed to attach to Accelerator Sensor.");
        Toast.makeText(this, "Error! Failed to create accelerometer sensor!", Toast.LENGTH_LONG).show();
        cleanup();
    }

    mSensorManager.registerListener(this, mAccelerometerSensor, SensorManager.SENSOR_DELAY_UI);

    // setup the Accelerometer History plot:
    mAccelerometerPlot = (XYPlot) findViewById(R.id.accelerometerPlot);
    mFftPlot = (XYPlot) findViewById(R.id.fftPlot);

    mAccelerometerPlot.setRangeBoundaries(-25, 25, BoundaryMode.FIXED);
    mAccelerometerPlot.setDomainBoundaries(0, mWindowSize - 1, BoundaryMode.FIXED);

    mFftPlot.setRangeBoundaries(0, 250, BoundaryMode.FIXED);
    mFftPlot.setDomainBoundaries(0, mWindowSize / 2, BoundaryMode.AUTO);
    mFftPlot.setDomainStep(XYStepMode.SUBDIVIDE, 10);
    //mFftPlot.setRangeStep(XYStepMode.INCREMENT_BY_VAL, 50);

    mAccelerometerXSeries = new SimpleXYSeries("X");
    mAccelerometerXSeries.useImplicitXVals();
    mAccelerometerYSeries = new SimpleXYSeries("Y");
    mAccelerometerYSeries.useImplicitXVals();
    mAccelerometerZSeries = new SimpleXYSeries("Z");
    mAccelerometerZSeries.useImplicitXVals();
    mAccelerometerMSeries = new SimpleXYSeries("magnitude");
    mAccelerometerMSeries.useImplicitXVals();

    mFftSeries = new SimpleXYSeries("FFT");
    mFftSeries.useImplicitXVals();

    mFftPlot.addSeries(mFftSeries, new LineAndPointFormatter(Color.rgb(0, 0, 0), null, null, null));

    mAccelerometerPlot.addSeries(mAccelerometerXSeries,
            new LineAndPointFormatter(Color.rgb(100, 100, 200), null, null, null));
    mAccelerometerPlot.addSeries(mAccelerometerYSeries,
            new LineAndPointFormatter(Color.rgb(100, 200, 100), null, null, null));
    mAccelerometerPlot.addSeries(mAccelerometerZSeries,
            new LineAndPointFormatter(Color.rgb(200, 100, 100), null, null, null));
    mAccelerometerPlot.addSeries(mAccelerometerMSeries,
            new LineAndPointFormatter(Color.rgb(0, 0, 0), null, null, null));
    mAccelerometerPlot.setDomainStepValue(5);
    mAccelerometerPlot.setTicksPerRangeLabel(3);
    mAccelerometerPlot.setDomainLabel("Sample Index");
    mAccelerometerPlot.getDomainLabelWidget().pack();
    mAccelerometerPlot.setRangeLabel("m/s^2");
    mAccelerometerPlot.getRangeLabelWidget().pack();

    final PlotStatistics histStats = new PlotStatistics(1000, false);
    mAccelerometerPlot.addListener(histStats);

    // perform hardware accelerated rendering of the plots
    mAccelerometerPlot.setLayerType(View.LAYER_TYPE_NONE, null);
    mFftPlot.setLayerType(View.LAYER_TYPE_NONE, null);

    mFftPlot.setTicksPerRangeLabel(5);
    mFftPlot.setTicksPerDomainLabel(1);

    mSampleRateSeekBar = (SeekBar) findViewById(R.id.sampleRateSeekBar);
    mSampleRateSeekBar.setMax((SAMPLE_MAX_VALUE - SAMPLE_MIN_VALUE) / SAMPLE_STEP);
    mSampleRateSeekBar.setOnSeekBarChangeListener(this);

    mFftWindowSeekBar = (SeekBar) findViewById(R.id.fftWindowSeekBar);
    mFftWindowSeekBar.setMax((WINDOW_MAX_VALUE - WINDOW_MIN_VALUE) / WINDOW_STEP);
    mFftWindowSeekBar.setOnSeekBarChangeListener(this);

    mWindowSizeTextView = (TextView) findViewById(R.id.windowSizeTextView);

    // Perform FFT calculations in background thread
    mFft = new FFT(mWindowSize);
    Runnable r = new PerformFft();
    mFftThread = new Thread(r);
    mFftThread.start();

    mNotificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_help_outline_black_24dp).setContentTitle("MIS Ex3 Activity Recognizer")
            .setContentText("Trying to guess your activity").setOngoing(true);

    Intent resultIntent = new Intent(this, MainActivity.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mNotificationBuilder.setContentIntent(resultPendingIntent);

    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(mNotificationId, mNotificationBuilder.build());

    Runnable detectActivity = new DetectActivity();
    mDetectActivityThread = new Thread(detectActivity);
    mDetectActivityThread.start();
}

From source file:ch.fhnw.comgr.GLES3Activity.java

@Override
protected void onResume() {
    Log.i(TAG, "GLES3Activity.onResume");
    super.onResume();
    myView.onResume();/*from  www.j av a2 s .  c o  m*/

    if (mSensorManager != null)
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_FASTEST);
}

From source file:io.github.data4all.service.OrientationListener.java

@Override
public void onCreate() {
    sManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    accelerometer = sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    magnetometer = sManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

    sManager.registerListener(this, sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_NORMAL);
    sManager.registerListener(this, sManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
            SensorManager.SENSOR_DELAY_NORMAL);
}

From source file:org.cocos2dx.lib.Cocos2dxAccelerometer.java

@Override
public void onSensorChanged(SensorEvent event) {

    if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
        return;/*w w  w  .  j  a v  a2 s . co  m*/
    }

    float x = event.values[0];
    float y = event.values[1];
    float z = event.values[2];

    /*
     * Because the axes are not swapped when the device's screen orientation changes. 
     * So we should swap it here.
     * In tablets such as Motorola Xoom, the default orientation is landscape, so should
     * consider this.
     */
    int orientation = mContext.getResources().getConfiguration().orientation;
    if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (mNaturalOrientation != Surface.ROTATION_0)) {
        float tmp = x;
        x = -y;
        y = tmp;
    } else if ((orientation == Configuration.ORIENTATION_PORTRAIT)
            && (mNaturalOrientation != Surface.ROTATION_0)) {
        float tmp = x;
        x = y;
        y = -tmp;
    }

    onSensorChanged(x, y, z, event.timestamp);
    // Log.d(TAG, "x = " + event.values[0] + " y = " + event.values[1] + " z = " + event.values[2]);
}

From source file:com.developer.shade.sensors.SensorService.java

@Override
public void onCreate() {
    Log.d("Running onCreate", "Obtaining Device Accelerometer Hardware Sensor");
    senManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    Sensor sensor = senManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    Log.d("NAME: ", sensor.getName());
    initNotification();//from  ww  w .java2 s  .  com
    super.onCreate();
}

From source file:eu.intermodalics.tango_ros_streamer.ImuNode.java

@Override
public void onSensorChanged(SensorEvent event) {
    switch (event.sensor.getType()) {
    case Sensor.TYPE_ROTATION_VECTOR:
        mNewRotationData = true;//from  ww w .j  a  v a2 s  . c  om
        float[] quaternion = new float[4];
        SensorManager.getQuaternionFromVector(quaternion, event.values);
        mImuMessage.getOrientation().setW(quaternion[0]);
        mImuMessage.getOrientation().setX(quaternion[1]);
        mImuMessage.getOrientation().setY(quaternion[2]);
        mImuMessage.getOrientation().setZ(quaternion[3]);
        mImuMessage.setOrientationCovariance(new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 });
        break;
    case Sensor.TYPE_GYROSCOPE:
        mNewGyroscopeData = true;
        mImuMessage.getAngularVelocity().setX(event.values[0]);
        mImuMessage.getAngularVelocity().setY(event.values[1]);
        mImuMessage.getAngularVelocity().setZ(event.values[2]);
        mImuMessage.setAngularVelocityCovariance(new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 });
        break;
    case Sensor.TYPE_ACCELEROMETER:
        mNewAccelerometerData = true;
        mImuMessage.getLinearAcceleration().setX(event.values[0]);
        mImuMessage.getLinearAcceleration().setY(event.values[1]);
        mImuMessage.getLinearAcceleration().setZ(event.values[2]);
        mImuMessage.setLinearAccelerationCovariance(new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 });
        break;
    default:
        break;
    }
    if (mNewRotationData && mNewGyroscopeData && mNewAccelerometerData) {
        mImuMessage.getHeader().setStamp(mConnectedNode.getCurrentTime());
        mImuMessage.getHeader().setFrameId("imu");
        mImuPublisher.publish(mImuMessage);
        mNewRotationData = false;
        mNewGyroscopeData = false;
        mNewAccelerometerData = false;
    }
}

From source file:edu.cens.loci.sensors.AccelerometerHandler.java

public void start() {

    if (mIsOn)//from w w  w .  ja v  a 2 s . c om
        return;

    mCpuLock = cpu().newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AccelerometerHandler.CpuLock");
    mCpuLock.setReferenceCounted(false);

    mIsOn = true;

    if (mDuration > 0) {
        //mCpuLock.acquire();
        mOnTimer = new Timer("sensorTurnOnTimer");
        mOffTimer = new Timer("sensorTurnOffTimer");

        mOnTimer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                mSensorService = (SensorManager) mCxt.getSystemService(Context.SENSOR_SERVICE);

                synchronized (this) {
                    MyLog.i(LociConfig.D.ACC, TAG, "[ACC] ON ");
                    mCpuLock.acquire();
                    mSensorOn = true;
                    mSensorService.registerListener(sInstance,
                            mSensorService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), mRate);
                }
            }
        }, 0, mPeriod);

        mOffTimer.scheduleAtFixedRate(new TimerTask() {
            public void run() {

                synchronized (this) {
                    MyLog.i(LociConfig.D.ACC, TAG, "[ACC] OFF ");
                    mSensorOn = false;
                    if (mCpuLock.isHeld())
                        mCpuLock.release();
                    mSensorService.unregisterListener(sInstance,
                            mSensorService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));
                }
                // time to turn off sensor -- somehow send data

                //mXArr.reset();
                //mYArr.reset();
                //mZArr.reset();
                long time = Calendar.getInstance().getTime().getTime();
                float magVar = getMagnitudeVariance();
                //LociMobileManagerService.getInstance().eventAccelerometerResult(Calendar.getInstance().getTime().getTime(), magVar);

                mListener.onAccelerometerChanged(time, magVar);

                //if (LociMobileManagerService.getInstance().isMDOn()) 
                //   LociMobileManagerService.getInstance().getSystemDb().updatePowerRow(SystemLogDbAdapter.SENSOR_ACC, System.currentTimeMillis());
            }
        }, mDuration, mPeriod);

    } else {

        mCpuLock.acquire();
        mSensorService = (SensorManager) mCxt.getSystemService(Context.SENSOR_SERVICE);
        mSensorService.registerListener(this, mSensorService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                mRate);

        mReportTimer = new Timer("SensorReportTimer");
        mReportTimer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                // send data
                long time = Calendar.getInstance().getTime().getTime();
                float magVar = getMagnitudeVariance();
                mListener.onAccelerometerChanged(time, magVar);
                //LociMobileManagerService.getInstance().eventAccelerometerResult(Calendar.getInstance().getTime().getTime(), magVar);
                //if (LociMobileManagerService.getInstance().isMDOn()) 
                //   LociMobileManagerService.getInstance().getSystemDb().updatePowerRow(SystemLogDbAdapter.SENSOR_ACC, System.currentTimeMillis());
            }
        }, 0, mDuration);
    }

    //LociMobileManagerService.getInstance().getSystemDb().addPowerRow(SystemLogDbAdapter.SENSOR_ACC, System.currentTimeMillis());
    startChkTimer();
}

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

public void registerSensor(Sensor mSensor) {
    LocationListener locationListener = new LocationListener() {
        @Override/*ww w  .j  av  a2s.c o 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:org.mozilla.mozstumbler.service.stumblerthread.motiondetection.LegacyMotionSensor.java

@Override
public void start() {
    mSensorManager.registerListener(mSensorEventListener,
            mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);

    isActive = true;/* ww w . j  ava 2s.co m*/
}

From source file:com.bolatu.gezkoncsvlogger.GyroOrientation.GyroscopeOrientation.java

protected void calculateOrientationAccelMag() {
    super.calculateOrientationAccelMag();

    getRotationVectorFromAccelMag();//from w w  w. j  a  va  2s .  c  o m

    // The acceleration and magnetic sensors are only required for the
    // initial orientation. We can stop listening for updates after we
    // obtain the initial orientation.
    if (isOrientationValidAccelMag) {
        sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));
        sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD));
    }
}