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:com.dragon4.owo.ar_trace.ARCore.MixView.java

public void onSensorChanged(SensorEvent evt) {
    try {//from  w ww . j  a v a2  s .  co  m
        //         killOnError();

        // ?? , ?  ???  ? ? ? 
        if (evt.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            grav[0] = evt.values[0];
            grav[1] = evt.values[1];
            grav[2] = evt.values[2];

            augScreen.postInvalidate(); // ? 
        } else if (evt.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            mag[0] = evt.values[0];
            mag[1] = evt.values[1];
            mag[2] = evt.values[2];

            augScreen.postInvalidate(); // ? 
        }

        //  ? 
        SensorManager.getRotationMatrix(RTmp, I, grav, mag);
        //  (?)
        SensorManager.remapCoordinateSystem(RTmp, SensorManager.AXIS_X, SensorManager.AXIS_MINUS_Z, Rot);

        //  ? ? 
        tempR.set(Rot[0], Rot[1], Rot[2], Rot[3], Rot[4], Rot[5], Rot[6], Rot[7], Rot[8]);

        //       ,  
        finalR.toIdentity();
        finalR.prod(m4);
        finalR.prod(m1);
        finalR.prod(tempR);
        finalR.prod(m3);
        finalR.prod(m2);
        finalR.invert();

        // ? ?  ? ??   ...
        histR[rHistIdx].set(finalR);
        rHistIdx++;
        if (rHistIdx >= histR.length)
            rHistIdx = 0;

        smoothR.set(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f);
        for (int i = 0; i < histR.length; i++) {
            smoothR.add(histR[i]);
        }
        smoothR.mult(1 / (float) histR.length);

        synchronized (mixContext.rotationM) {
            mixContext.rotationM.set(smoothR);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.cellbots.logger.LoggerActivity.java

private void updateSensorUi(int sensorType, int accuracy, float[] values) {
    // IMPORTANT: DO NOT UPDATE THE CONTENTS INSIDE A DRAWER IF IT IS BEING
    // ANIMATED VIA A CALL TO animateOpen/animateClose!!!
    // Updating anything inside will stop the animation from running.
    // Note that this does not seem to affect the animation if it had been
    // triggered by dragging the drawer instead of being called
    // programatically.
    if (mDataDrawer.isMoving()) {
        return;//from   w ww .  java2s . c o  m
    }
    TextView xTextView;
    TextView yTextView;
    TextView zTextView;
    if (sensorType == Sensor.TYPE_ACCELEROMETER) {
        xTextView = mAccelXTextView;
        yTextView = mAccelYTextView;
        zTextView = mAccelZTextView;
    } else if (sensorType == Sensor.TYPE_GYROSCOPE) {
        xTextView = mGyroXTextView;
        yTextView = mGyroYTextView;
        zTextView = mGyroZTextView;
    } else if (sensorType == Sensor.TYPE_MAGNETIC_FIELD) {
        xTextView = mMagXTextView;
        yTextView = mMagYTextView;
        zTextView = mMagZTextView;
    } else {
        return;
    }

    int textColor = Color.WHITE;
    String prefix = "";
    switch (accuracy) {
    case SensorManager.SENSOR_STATUS_ACCURACY_HIGH:
        prefix = "  ";
        break;
    case SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM:
        prefix = "  *";
        break;
    case SensorManager.SENSOR_STATUS_ACCURACY_LOW:
        prefix = "  **";
        break;
    case SensorManager.SENSOR_STATUS_UNRELIABLE:
        prefix = "  ***";
        break;
    }

    xTextView.setTextColor(textColor);
    yTextView.setTextColor(textColor);
    zTextView.setTextColor(textColor);
    xTextView.setText(prefix + numberDisplayFormatter(values[0]));
    yTextView.setText(prefix + numberDisplayFormatter(values[1]));
    zTextView.setText(prefix + numberDisplayFormatter(values[2]));

}

From source file:com.kircherelectronics.accelerationfilter.activity.AccelerationPlotActivity.java

/**
 * Set the sensor delay based on user preferences. 0 = slow, 1 = medium, 2 =
 * fast./*from w ww.  j a va2  s .c  om*/
 * 
 * @param position
 *            The desired sensor delay.
 */
private void setSensorDelay(int position) {
    switch (position) {
    case 0:

        sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));

        // Register for sensor updates.
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
        break;
    case 1:

        sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));

        // Register for sensor updates.
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_GAME);
        break;
    case 2:

        sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));

        // Register for sensor updates.
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_FASTEST);
        break;
    }

    lpf.reset();
    meanFilter.reset();
}

From source file:mp.teardrop.PlaybackService.java

/**
 * Setup the accelerometer.//from   ww w.  j  av a 2s.com
 */
private void setupSensor() {
    if (mShakeAction == Action.Nothing || (mState & FLAG_PLAYING) == 0) {
        if (mSensorManager != null)
            mSensorManager.unregisterListener(this);
    } else {
        if (mSensorManager == null)
            mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_UI);
    }
}

From source file:cl.ipp.katbag.fragment.Player.java

@Override
public void onSensorChanged(SensorEvent event) {
    synchronized (this) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            long curTime = System.currentTimeMillis();
            // only allow one update every 100ms.
            if ((curTime - lastUpdate) > 100) {
                long diffTime = (curTime - lastUpdate);
                lastUpdate = curTime;/*w  w  w. jav a  2s. c o  m*/

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

                float speed = (float) Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

                if (speed > SHAKE_THRESHOLD) {

                    for (int i = 0; i < shakeBgn.size(); i++)
                        setBranchTreeCondition(shakeId.get(i), 1);

                    for (int i = 0; i < shakeBgn.size(); i++) {

                        if (checkTreeCondition(shakeId.get(i))) {
                            Log.d("ply", "shake - ini:" + shakeBgn.get(i) + ", last:" + shakeLst.get(i));
                            play(shakeBgn.get(i), shakeLst.get(i) + 1);
                        }
                    }

                    for (int i = 0; i < shakeBgn.size(); i++)
                        setBranchTreeCondition(shakeId.get(i), 0);
                }

                last_x = x;
                last_y = y;
                last_z = z;
            }
        }
    }
}

From source file:org.mixare.MixViewActivity.java

public void onSensorChanged(SensorEvent evt) {
    try {//from  www  .j  av  a  2 s . com
        if (getMixViewData().getSensorGyro() != null) {

            if (evt.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
                getMixViewData().setGyro(evt.values);
            }

            if (evt.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                getMixViewData().setGrav(
                        getMixViewData().getGravFilter().lowPassFilter(evt.values, getMixViewData().getGrav()));
            } else if (evt.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                getMixViewData().setMag(
                        getMixViewData().getMagFilter().lowPassFilter(evt.values, getMixViewData().getMag()));
            }
            getMixViewData().setAngle(getMixViewData().getMagFilter().complementaryFilter(
                    getMixViewData().getGrav(), getMixViewData().getGyro(), 30, getMixViewData().getAngle()));

            SensorManager.getRotationMatrix(getMixViewData().getRTmp(), getMixViewData().getI(),
                    getMixViewData().getGrav(), getMixViewData().getMag());
        } else {
            if (evt.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                getMixViewData().setGrav(evt.values);
            } else if (evt.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                getMixViewData().setMag(evt.values);
            }
            SensorManager.getRotationMatrix(getMixViewData().getRTmp(), getMixViewData().getI(),
                    getMixViewData().getGrav(), getMixViewData().getMag());
        }

        //         augmentedView.postInvalidate();
        hudView.postInvalidate();
        projectedMapView.postInvalidate();

        int rotation = Compatibility.getRotation(this);

        if (rotation == 1) {
            SensorManager.remapCoordinateSystem(getMixViewData().getRTmp(), SensorManager.AXIS_X,
                    SensorManager.AXIS_MINUS_Z, getMixViewData().getRot());
        } else {
            SensorManager.remapCoordinateSystem(getMixViewData().getRTmp(), SensorManager.AXIS_Y,
                    SensorManager.AXIS_MINUS_Z, getMixViewData().getRot());
        }
        getMixViewData().getTempR().set(getMixViewData().getRot()[0], getMixViewData().getRot()[1],
                getMixViewData().getRot()[2], getMixViewData().getRot()[3], getMixViewData().getRot()[4],
                getMixViewData().getRot()[5], getMixViewData().getRot()[6], getMixViewData().getRot()[7],
                getMixViewData().getRot()[8]);

        getMixViewData().getFinalR().toIdentity();
        getMixViewData().getFinalR().prod(getMixViewData().getM4());
        getMixViewData().getFinalR().prod(getMixViewData().getM1());
        getMixViewData().getFinalR().prod(getMixViewData().getTempR());
        getMixViewData().getFinalR().prod(getMixViewData().getM3());
        getMixViewData().getFinalR().prod(getMixViewData().getM2());
        getMixViewData().getFinalR().invert();

        getMixViewData().getHistR()[getMixViewData().getrHistIdx()].set(getMixViewData().getFinalR());

        int histRLenght = getMixViewData().getHistR().length;

        getMixViewData().setrHistIdx(getMixViewData().getrHistIdx() + 1);
        if (getMixViewData().getrHistIdx() >= histRLenght)
            getMixViewData().setrHistIdx(0);

        getMixViewData().getSmoothR().set(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f);
        for (int i = 0; i < histRLenght; i++) {
            getMixViewData().getSmoothR().add(getMixViewData().getHistR()[i]);
        }
        getMixViewData().getSmoothR().mult(1 / (float) histRLenght);

        MixContext.getInstance().updateSmoothRotation(getMixViewData().getSmoothR());

        //         float[] orientation = new float[3];
        //            float[] rTemp = getMixViewData().getRTmp();
        //         SensorManager.getOrientation(rTemp, orientation);
        //            Log.d("PROJECT_MAP", "Sensor Angles");
        //         Log.d("PROJECT_MAP", orientation[0] + ", " + orientation[1] + ", " + orientation[2]);
        //            Log.d("PROJECT_MAP", "Rotation Matrix Before Smoothing");
        //            Log.d("PROJECT_MAP", rTemp[0] + ", " + rTemp[1] + ", " + rTemp[2]);
        //            Log.d("PROJECT_MAP", rTemp[3] + ", " + rTemp[4] + ", " + rTemp[5]);
        //            Log.d("PROJECT_MAP", rTemp[6] + ", " + rTemp[7] + ", " + rTemp[8]);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.ichi2.anki2.Reviewer.java

@Override
protected void onResume() {
    mInBackground = false;//from w  w  w.ja  v a2 s . c  o m
    super.onResume();
    // Decks deck = DeckManager.getMainDeck();
    // if (deck == null) {
    // Log.e(AnkiDroidApp.TAG, "Reviewer: Deck already closed, returning to study options");
    // closeReviewer(RESULT_DECK_CLOSED, false);
    // return;
    // }

    // check if deck is already opened in big widget. If yes, reload card (to make sure it's not answered yet)
    // if (DeckManager.deckIsOpenedInBigWidget(deck.getDeckPath()) && mCurrentCard != null && !mInEditor) {
    // Log.i(AnkiDroidApp.TAG, "Reviewer: onResume: get card from big widget");
    // blockControls();
    // AnkiDroidWidgetBig.updateWidget(AnkiDroidWidgetBig.UpdateService.VIEW_NOT_SPECIFIED, true);
    // DeckTask.launchDeckTask(DeckTask.TASK_TYPE_ANSWER_CARD, mAnswerCardHandler, new DeckTask.TaskData(0, deck,
    // null));
    // } else {
    restartTimer();
    // }
    //
    if (mShakeEnabled) {
        mSensorManager.registerListener(mSensorListener,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    }
}

From source file:com.hichinaschool.flashcards.anki.Reviewer.java

@Override
protected void onResume() {
    mInBackground = false;/*w w w . j a  v a  2  s .  c o m*/
    super.onResume();
    // Decks deck = DeckManager.getMainDeck();
    // if (deck == null) {
    // Log.e(AnkiDroidApp.TAG, "Reviewer: Deck already closed, returning to study options");
    // closeReviewer(RESULT_DECK_CLOSED, false);
    // return;
    // }

    // check if deck is already opened in big widget. If yes, reload card (to make sure it's not answered yet)
    // if (DeckManager.deckIsOpenedInBigWidget(deck.getDeckPath()) && mCurrentCard != null && !mInEditor) {
    // // Log.i(AnkiDroidApp.TAG, "Reviewer: onResume: get card from big widget");
    // blockControls();
    // AnkiDroidWidgetBig.updateWidget(AnkiDroidWidgetBig.UpdateService.VIEW_NOT_SPECIFIED, true);
    // DeckTask.launchDeckTask(DeckTask.TASK_TYPE_ANSWER_CARD, mAnswerCardHandler, new DeckTask.TaskData(0, deck,
    // null));
    // } else {
    restartTimer();
    // }
    //
    if (mShakeEnabled) {
        mSensorManager.registerListener(mSensorListener,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    }
}

From source file:com.updetector.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /**//from  w  ww.j  a  va2  s . c  o m
     * Set the views
     */
    // Set the main layout
    setContentView(R.layout.activity_main);

    // get a handle to the console textview
    consoleTextView = (TextView) findViewById(R.id.console_text_id);
    consoleTextView.setMovementMethod(new ScrollingMovementMethod());

    //setup monitoring fields
    environTextView = (TextView) findViewById(R.id.environment);
    environTextView.setText(ENVIRONMENT_PREFIX + CommonUtils.eventCodeToString(lastEnvironment));
    stateTextView = (TextView) findViewById(R.id.state);

    //stateTextView.setText(STATE_PREFIX+"unknown");

    googleStateTextView = (TextView) findViewById(R.id.google_state);
    googleStateTextView.setText(GOOGLE_MOBILITY_STATE_PREFIX + "unknown");

    //indicatorTextView=(TextView) findViewById(R.id.indicator);
    //indicatorTextView.setText(INDICATOR_PREFIX);

    // set up the map view
    setupMapIfNeeded();
    //set up the location client
    setupLocationClientIfNeeded();

    /**
     * set up color coded map
     */
    if (parkingBlocks == null) {
        parkingBlocks = ParkingBlocks.GetParkingBlocks();
        showAvailabilityMap();
    }

    mTextToSpeech = new TextToSpeech(this, this);
    mCalendar = Calendar.getInstance();

    /*
     * Initialize managers
     */
    // Instantiate an adapter to store update data from the log
    /*           mStatusAdapter = new ArrayAdapter<Spanned>(
           this,
           R.layout.item_layout,
           R.id.log_text
               );*/

    // Set the broadcast receiver intent filer
    mBroadcastManager = LocalBroadcastManager.getInstance(this);

    // Create a new Intent filter for the broadcast receiver
    mBroadcastFilter = new IntentFilter(Constants.ACTION_REFRESH_STATUS_LIST);
    mBroadcastFilter.addCategory(Constants.CATEGORY_LOCATION_SERVICES);
    mBroadcastFilter.addAction(Constants.BLUETOOTH_CONNECTION_UPDATE);
    mBroadcastFilter.addAction(Constants.GOOGLE_ACTIVITY_RECOGNITION_UPDATE);
    mBroadcastManager.registerReceiver(mBroadcastReceiver, mBroadcastFilter);

    // Get the instance of the customized notification manager
    mDetectionNotificationManager = DetectionNotificationManager.getInstance(this);

    //Get the FusionManager object
    mFusionManager = new FusionManager(this);

    // Get the ClassificationManager object
    mClassificationManager = ClassificationManager.getInstance(this);

    //TODO  train classifiers if necessary
    if (Constants.IS_TRAINING_MODE) {
        int[] classifiersToBeTrained = { Constants.ACCEL_MOTION_STATE };
        for (int classifier : classifiersToBeTrained) {
            mClassificationManager.mClassfiers.get(classifier).train();
        }
    }

    //get the sensor service
    mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
    //get the accelerometer sensor
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mSensorManager.registerListener(mSensorEventListener, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);

    mAudioRecordManager = AudioRecordManager.getInstance();

    // Get the WakeLockManager object
    mWakeLockManager = WakeLockManager.getInstance(this);
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // Get the LogManager object
    mLogManager = LogManager.getInstance(this);
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mXPSHandler = new XPS(this);
    mXPSHandler.setRegistrationUser(new WPSAuthentication("dbmc", "uic"));
    //mXPSHandler.setTiling("", 0, 0,  null);

    /**
     * Initialize IODetector
     */
    cellTowerChart = new CellTowerChart((TelephonyManager) getSystemService(TELEPHONY_SERVICE), this);
    magnetChart = new MagnetChart(mSensorManager, this);
    lightChart = new LightChart(mSensorManager, this);

    //new AggregatedIODetector().execute("");//Check the detection for the first time

    //This timer handle starts the aggregated calculation for the detection
    //Interval 1 seconds.
    Timer uiTimer = new Timer();
    mIODectorHandler = new Handler();

    /*uiTimer.scheduleAtFixedRate(new TimerTask() {
       private int walked = 0;
       @Override
       public void run() {
    mIODectorHandler.post(new Runnable() {
       @Override
       public void run() {
          if(phoneNotStill){//Check if the user is walking
             walked++;
          }
          else{
             walked = 0;
          }
          if(aggregationFinish && walked > 3){//Check if the user has walked for at least 3 second, and the previous calculation has been finish
             aggregationFinish = false;
             walked = 0;
             new AggregatedIODetector().execute("");
          }
            
       }
    });
       }
    }, 0, 1000);*/

    /**
      * Initialize fields other than managers
      */
    lastAccReading = new double[3];

    /**
      * Startup routines
      */
    // catch the force close error
    Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(MainActivity.this));

    /**
     * Start Google Activity Recognition
     */
    mGoogleActivityDetectionRequester = new GoogleActivityRecognitionClientRequester(this);
    mGoogleActivityDetectionRemover = new GoogleActivityRecognitionClientRemover(this);
    startGoogleActivityRecognitionUpdates(null);

    checkGPSEnabled();

    //test record sample
    //mAudioRecordManager.recordAudioSample("/sdcard/audio.wav");

    //Test extract features from audio files
    //String features=AudioFeatureExtraction.extractFeatures(this, "/sdcard/bus6.wav");
    //mClassificationManager.mClassfiers.get(Constants.SENSOR_MICROPHONE).classify(features);

}

From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java

private void registerAccelerometerListener() {
    final SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

    sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_FASTEST);
}