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.javadog.cgeowear.cgeoWear.java

/**
 * Interprets watch compass if user has requested that feature.
 *//*from  w  w w . j  a v  a 2  s .  c  o  m*/
@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        gravity = event.values.clone();
    } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        geomagnetic = event.values.clone(); //TODO: Some watches don't let me access the compass correctly yet.
    }

    if (gravity != null && geomagnetic != null) {
        float[] R = new float[9];
        float[] I = new float[9];

        boolean success = SensorManager.getRotationMatrix(R, I, gravity, geomagnetic);
        if (success) {
            float[] orientation = new float[3];
            SensorManager.getOrientation(R, orientation);
            float azimuth = (float) Math.toDegrees(orientation[0]);

            if (currentLocation != null) {
                float smoothedLatitude = smoothSensorValues(oldLatitude, (float) currentLocation.getLatitude(),
                        1 / 3f);
                float smoothedLongitude = smoothSensorValues(oldLongitude,
                        (float) currentLocation.getLongitude(), 1 / 3f);
                float smoothedAltitude = smoothSensorValues(oldAltitude, (float) currentLocation.getAltitude(),
                        1 / 3f);

                GeomagneticField geomagneticField = new GeomagneticField(smoothedLatitude, smoothedLongitude,
                        smoothedAltitude, System.currentTimeMillis());
                azimuth += geomagneticField.getDeclination();

                float bearing = currentLocation.bearingTo(geocacheLocation);

                direction = smoothSensorValues(oldDirection, -(azimuth - bearing), 1 / 5f);

                //Set old values to current values (for smoothing)
                oldDirection = direction;
                oldLatitude = smoothedLatitude;
                oldLongitude = smoothedLongitude;
                oldAltitude = smoothedAltitude;

                //Display direction on compass if update interval has passed
                long currentTime = System.currentTimeMillis();
                if ((currentTime - prevTime) > DIRECTION_UPDATE_SPEED) {
                    rotateCompass(direction);
                    prevTime = currentTime;
                }
            }
        }
    }
}

From source file:com.samebits.beacon.locator.ui.view.RadarScanView.java

private synchronized void calcBearing(SensorEvent event) {

    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        System.arraycopy(event.values, 0, mLastAccelerometer, 0, event.values.length);
        mLastAccelerometerSet = true;/*w w  w  .  jav  a 2 s.  com*/
    } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.length);
        mLastMagnetometerSet = true;
    }
    if (mLastAccelerometerSet && mLastMagnetometerSet) {

        /* Create rotation Matrix */
        float[] rotationMatrix = new float[9];
        if (SensorManager.getRotationMatrix(rotationMatrix, null, mLastAccelerometer, mLastMagnetometer)) {
            SensorManager.getOrientation(rotationMatrix, mOrientation);

            float azimuthInRadians = mOrientation[0];

            angleLowpassFilter.add(azimuthInRadians);

            mLast_bearing = (float) (Math.toDegrees(angleLowpassFilter.average()) + 360) % 360;

            postInvalidate();

            //Log.d(Constants.TAG, "orientation bearing: " + mLast_bearing);

        }
    }
}

From source file:au.gov.ga.worldwind.androidremote.client.Remote.java

@Override
protected void onResume() {
    super.onResume();

    // Performing this check in onResume() covers the case in which BT was
    // not enabled during onStart(), so we were paused to enable it...
    // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
    if (communicator != null && communicator.getState() == AndroidCommunicator.State.NONE) {
        communicator.start();/*from  w ww .jav  a2s. c  o  m*/
        remoteViewCommunicator.start();
    }

    updateActionBarIcon(communicator.getState());
    sensorManager.registerListener(sensorListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_FASTEST);
}

From source file:com.thalmic.android.sample.helloworld.HelloWorldActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hello_world);

    sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
    vector = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
    acc = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mag = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

    mLockStateView = (TextView) findViewById(R.id.lock_state);
    mTextView = (TextView) findViewById(R.id.text);
    mRoll = (TextView) findViewById(R.id.roll);
    mPitch = (TextView) findViewById(R.id.pitch);
    mYaw = (TextView) findViewById(R.id.yaw);

    EditText videoip = (EditText) findViewById(R.id.videoip);
    videoip.setOnEditorActionListener(new OnEditorActionListener() {
        @Override/* w ww  . j a  v a 2  s  .c  om*/
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                ip = v.getText().toString();
                startVideo();
                handled = true;
            }

            return handled;
        }
    });

    EditText connect = (EditText) findViewById(R.id.connect);
    connect.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_SEND) {

                try {
                    String address = v.getText().toString();
                    client = new Client(("tcp://" + address + ":6767"), "client");

                    try {
                        client.send("runtime", "getUptime");
                        //client.send("runtime", "start", "arduino", "Arduino");
                        //client.send("runtime", "start", "servo01", "Servo");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                handled = true;
            }
            return handled;
        }
    });

    EditText comPort = (EditText) findViewById(R.id.comport);
    comPort.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                String address = v.getText().toString();
                if (client != null) {
                    try {
                        client.send("arduino", "connect", address);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                handled = true;
            }
            return handled;
        }
    });

    final Button calibrate = (Button) findViewById(R.id.calibrate);
    calibrate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //
            // Perform action on click
            if (client != null) {
                try {
                    client.send("oculus", "calibrate");
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    });

    ToggleButton toggleCardboard = (ToggleButton) findViewById(R.id.cardboard);
    toggleCardboard.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                cardboardMode = true;
            } else {
                cardboardMode = false;
            }
        }
    });

    ToggleButton toggleHeadTracking = (ToggleButton) findViewById(R.id.headTrackingButton);
    toggleHeadTracking.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                headTrackingMode = true;
            } else {
                headTrackingMode = false;
            }
        }
    });

    // First, we initialize the Hub singleton with an application identifier.
    Hub hub = Hub.getInstance();
    if (!hub.init(this, getPackageName())) {
        // We can't do anything with the Myo device if the Hub can't be initialized, so exit.
        Toast.makeText(this, "Couldn't initialize Hub", Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
    // Next, register for DeviceListener callbacks.
    hub.addListener(mListener);
    //hub.attachToAdjacentMyo();
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

From source file:com.google.android.apps.santatracker.doodles.tilt.SwimmingFragment.java

@Override
protected void firstPassLoadOnUiThread() {
    final FrameLayout.LayoutParams wrapperLP = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT);// ww w.  j  ava 2s  .  c  o m

    final SwimmingFragment that = this;
    scoreView = getScoreView();
    pauseView = getPauseView();

    int diveViewBottomMargin = (int) context.getResources().getDimension(R.dimen.dive_margin_bottom);
    int diveViewStartMargin = (int) context.getResources().getDimension(R.dimen.dive_margin_left);
    int diveViewSize = (int) context.getResources().getDimension(R.dimen.dive_image_size);

    FrameLayout.LayoutParams diveViewLP = new LayoutParams(diveViewSize, diveViewSize);
    diveViewLP.setMargins(diveViewStartMargin, 0, 0, diveViewBottomMargin);
    diveViewLP.gravity = Gravity.BOTTOM | Gravity.LEFT;

    if (VERSION.SDK_INT >= 17) {
        diveViewLP.setMarginStart(diveViewStartMargin);
    }
    diveView = new DiveView(context);

    countdownView = new TextView(context);
    countdownView.setGravity(Gravity.CENTER);
    countdownView.setTextColor(context.getResources().getColor(R.color.ui_text_yellow));
    countdownView.setTypeface(Typeface.DEFAULT_BOLD);
    countdownView.setText("0");
    countdownView.setVisibility(View.INVISIBLE);
    Locale locale = context.getResources().getConfiguration().locale;
    countdownView.setText(NumberFormat.getInstance(locale).format(3));
    Point screenDimens = AndroidUtils.getScreenSize();
    UIUtil.fitToBounds(countdownView, screenDimens.x / 10, screenDimens.y / 10);

    LinearLayout gameView = new LinearLayout(context);
    gameView.setOrientation(LinearLayout.VERTICAL);

    // Add game view.
    swimmingView = new SwimmingView(context);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT, 7);
    gameView.addView(swimmingView, lp);

    if (editorMode) {
        LinearLayout buttonWrapper = new LinearLayout(context);
        buttonWrapper.setOrientation(LinearLayout.HORIZONTAL);
        lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, 1);
        gameView.addView(buttonWrapper, lp);

        resetButton = getButton(R.string.reset_level, new OnClickListener() {
            @Override
            public void onClick(View v) {
                SwimmingModel level = levelManager.loadDefaultLevel();
                initializeLevel(level, false);

                getActivity().getSharedPreferences(context.getString(R.string.swimming), Context.MODE_PRIVATE)
                        .edit().putString(CURRENT_LEVEL_KEY, null).commit();
            }
        });
        deleteButton = getButton(R.string.delete_levels, new OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment dialogFragment = new DeleteLevelDialogFragment();
                dialogFragment.show(getActivity().getFragmentManager(), "delete");
            }
        });
        loadButton = getButton(R.string.load_level, new OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment dialogFragment = new LoadLevelDialogFragment(that);
                dialogFragment.show(getActivity().getFragmentManager(), "load");
            }
        });
        saveButton = getButton(R.string.save_level, new OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment dialogFragment = new SaveLevelDialogFragment(that);
                dialogFragment.show(getActivity().getFragmentManager(), "save");
            }
        });
        collisionModeButton = new ToggleButton(context);
        collisionModeButton.setText(R.string.scenery_mode);
        collisionModeButton.setTextOff(context.getString(R.string.scenery_mode));
        collisionModeButton.setTextOn(context.getString(R.string.collision_mode));
        collisionModeButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                model.collisionMode = isChecked;
            }
        });

        lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.MATCH_PARENT, 1);
        buttonWrapper.addView(deleteButton, lp);
        buttonWrapper.addView(resetButton, lp);
        buttonWrapper.addView(loadButton, lp);
        buttonWrapper.addView(saveButton, lp);
        buttonWrapper.addView(collisionModeButton, lp);
    }

    sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    if (accelerometerSensor == null) {
        // TODO: The game won't be playable without this, so what should we do?
        Log.d(TAG, "Accelerometer sensor is null");
    }
    displayRotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
            .getRotation();

    wrapper.addView(gameView, 0, wrapperLP);
    wrapper.addView(countdownView, 1);
    wrapper.addView(diveView, 2, diveViewLP);
    wrapper.addView(scoreView, 3);
    wrapper.addView(pauseView, 4);
}

From source file:fr.bde_eseo.eseomega.GantierActivity.java

@Override
public void onSensorChanged(SensorEvent event) {
    /*//from   w w w .java  2s.co m
    Sensor mySensor = event.sensor;
            
    if (mySensor.getType() == Sensor.TYPE_GYROSCOPE) {
    float x = event.values[0];
    float y = event.values[1];
    float z = event.values[2];
            
    if (view != null && view.getThread() != null)
        if (Math.abs(x) > 0.2)
            view.getThread().moveSprite_x(-x);
            
    //mView.setBall_y(screen_y);
    }*/

    switch (event.sensor.getType()) {
    case Sensor.TYPE_ACCELEROMETER:
        // copy new accelerometer data into accel array
        // then calculate new orientation
        System.arraycopy(event.values, 0, accel, 0, 3);
        calculateAccMagOrientation();
        break;

    case Sensor.TYPE_GYROSCOPE:
        // process gyro data
        gyroFunction(event);
        break;

    case Sensor.TYPE_MAGNETIC_FIELD:
        // copy new magnetometer data into magnet array
        System.arraycopy(event.values, 0, magnet, 0, 3);
        break;
    }
}

From source file:edu.sfsu.csc780.chathub.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    DesignUtils.applyColorfulTheme(this);
    setContentView(R.layout.activity_main);
    final Context context = this;

    soundPreference = this.getString(R.string.play_sounds);
    mSentSound = MediaPlayer.create(context, R.raw.sentmessage);
    mStartRecordSound = MediaPlayer.create(context, R.raw.recording_beep);

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    // Set default username is anonymous.
    mUsername = ANONYMOUS;/*w  ww.  j  a  v a 2s.co  m*/
    //Initialize Auth
    mAuth = FirebaseAuth.getInstance();
    mUser = mAuth.getCurrentUser();
    if (mUser == null) {
        startActivity(new Intent(this, SignInActivity.class));
        finish();
        return;
    } else {
        mUsername = mUser.getDisplayName();
        if (mUser.getPhotoUrl() != null) {
            mPhotoUrl = mUser.getPhotoUrl().toString();
        }
    }

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API).build();

    // Initialize ProgressBar and RecyclerView.
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(this);
    mLinearLayoutManager.setStackFromEnd(true);
    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mFirebaseAdapter = MessageUtil.getFirebaseAdapter(this, this, /* MessageLoadListener */
            mLinearLayoutManager, mMessageRecyclerView, mImageClickListener);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);
    mProgressBar.setVisibility(ProgressBar.INVISIBLE);

    DesignUtils.setBackground(this);

    mMessageEditText = (EditText) findViewById(R.id.messageEditText);
    mMessageEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(MSG_LENGTH_LIMIT) });
    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    });

    mSendButton = (FloatingActionButton) findViewById(R.id.sendButton);
    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Send messages on click.
            //mMessageRecyclerView.scrollToPosition(0);
            ChatMessage chatMessage = new ChatMessage(mMessageEditText.getText().toString(), mUsername,
                    mPhotoUrl);
            MessageUtil.send(chatMessage);
            if (mSharedPreferences.getBoolean(soundPreference, true)) {
                mSentSound.start();
            }
            mMessageEditText.setText("");
        }
    });

    mImageButton = (ImageButton) findViewById(R.id.shareImageButton);
    mImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pickImage();
        }
    });

    mLocationButton = (ImageButton) findViewById(R.id.locationButton);
    mLocationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //mLocationButton.setEnabled(false);
            featureFlag = 1;
            loadMap();
        }
    });

    mCameraButton = (ImageButton) findViewById(R.id.cameraButton);
    mCameraButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dispatchTakePhotoIntent();
        }
    });

    mVideoButton = (ImageButton) findViewById(R.id.videoButton);
    mVideoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dispatchRecordVideoIntent();
        }
    });

    mVoiceMessageButton = (ImageButton) findViewById(R.id.shareVoiceMessage);
    mVoiceMessageButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {

            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (mSharedPreferences.getBoolean(soundPreference, true)) {
                    mStartRecordSound.start();
                }
                while (mStartRecordSound.isPlaying())
                    ;
                startRecording();
                break;
            case MotionEvent.ACTION_UP:
                stopRecording();
                if (mSharedPreferences.getBoolean(soundPreference, true)) {
                    mSentSound.start();
                }
                break;
            }
            return false;
        }
    });

    //Initialize the Accelerometer for Shake function
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    // Use the accelerometer.
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mShakeDetector = new ShakeDetector();
    shakePreference = this.getString(R.string.shake_change_background);

    if (mSharedPreferences.getBoolean(shakePreference, true)) {
        //Shake to change bg
        mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
        mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() {
            @Override
            public void onShake(int count) {
                // if(count > 2)
                DesignUtils.setRandomBackground(context);
            }
        });
    }

}

From source file:com.javadog.cgeowear.WearService.java

/**
 * Handles compass rotation./*from w w w  .j a  v  a  2 s .  co m*/
 */
@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        gravity = event.values.clone();
    } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        geomagnetic = event.values.clone();
    }

    if (gravity != null && geomagnetic != null) {
        float[] R = new float[9];
        float[] I = new float[9];

        boolean success = SensorManager.getRotationMatrix(R, I, gravity, geomagnetic);
        if (success) {
            float[] orientation = new float[3];
            SensorManager.getOrientation(R, orientation);
            float azimuth = (float) Math.toDegrees(orientation[0]);
            float pitch = (float) Math.toDegrees(orientation[1]);

            if (currentLocation != null) {
                float smoothedLatitude = smoothSensorValues(oldLatitude, (float) currentLocation.getLatitude(),
                        1 / 3f);
                float smoothedLongitude = smoothSensorValues(oldLongitude,
                        (float) currentLocation.getLongitude(), 1 / 3f);
                float smoothedAltitude = smoothSensorValues(oldAltitude, (float) currentLocation.getAltitude(),
                        1 / 3f);

                GeomagneticField geomagneticField = new GeomagneticField(smoothedLatitude, smoothedLongitude,
                        smoothedAltitude, System.currentTimeMillis());
                azimuth += geomagneticField.getDeclination();

                float bearing = currentLocation.bearingTo(geocacheLocation);

                float direction = smoothSensorValues(oldDirection, -(azimuth - bearing), 1 / 5f);

                //If the user puts the phone in his/her pocket upside-down, invert the compass
                if (pitch > 0) {
                    direction += 180f;
                }

                //Set old values to current values (for smoothing)
                oldDirection = direction;
                oldLatitude = smoothedLatitude;
                oldLongitude = smoothedLongitude;
                oldAltitude = smoothedAltitude;

                //Send direction update to Android Wear if update interval has passed
                long currentTime = System.currentTimeMillis();
                if ((currentTime - prevTime) > DIRECTION_UPDATE_SPEED) {
                    wearInterface.sendDirectionUpdate(direction);
                    prevTime = currentTime;
                }
            }
        }
    }
}

From source file:com.cubic9.android.droidglove.Main.java

@Override
public void onSensorChanged(SensorEvent event) {
    Float[] avgAngles = new Float[3];
    float[] rotationMatrix = new float[9];
    float[] attitude = new float[3];

    switch (event.sensor.getType()) {
    case Sensor.TYPE_MAGNETIC_FIELD:
        geomagnetic = event.values.clone();
        break;//w w  w  .ja va  2 s  .c o m
    case Sensor.TYPE_ACCELEROMETER:
        gravity = event.values.clone();
        break;
    }

    if (geomagnetic != null && gravity != null) {
        SensorManager.getRotationMatrix(rotationMatrix, null, gravity, geomagnetic);
        SensorManager.getOrientation(rotationMatrix, attitude);

        if (!mInitirizedSensor) {
            if (mCountBeforeInit > 20) {
                mInitirizedSensor = true;
                initYaw = (float) Math.toDegrees(attitude[0]);
            } else {
                mCountBeforeInit++;
            }
        }

        for (int i = 0; i < 3; i++) {
            for (int j = AVERAGE_AMOUNT - 1; j > 0; j--) {
                mOrigAngles[i][j] = mOrigAngles[i][j - 1];
            }
        }

        mOrigAngles[0][0] = (float) Math.toDegrees(attitude[0]) - initYaw;
        mOrigAngles[1][0] = (float) Math.toDegrees(attitude[1]);
        mOrigAngles[2][0] = (float) Math.toDegrees(attitude[2]);

        for (int i = 0; i < 3; i++) {
            avgAngles[i] = 0f;
            for (int j = 0; j < AVERAGE_AMOUNT; j++) {
                avgAngles[i] += mOrigAngles[i][j];
            }
            avgAngles[i] /= AVERAGE_AMOUNT;
        }

        /*
         * textViewX.setText(avgAngles[0].toString());
         * textViewY.setText(avgAngles[1].toString());
         * textViewZ.setText(avgAngles[2].toString());
         * textViewGrip.setText(Float.toString(mYDiff));
         */

        // create message for send
        List<Object> valueList = new ArrayList<Object>();
        valueList.add(avgAngles[1]);
        valueList.add(avgAngles[0]);
        valueList.add(-avgAngles[2]);
        valueList.add(Integer.valueOf((int) mYDiff));
        OSCMessage message = new OSCMessage(OSC_ADDRESS_TO_PC, valueList);

        // send
        try {
            mSender.send(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:nl.vincentketelaars.mexen.activities.RollDice.java

@Override
protected void onResume() {
    super.onResume();
    Log.i("RollDice", "onResume");
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    throwOnShake = sp.getBoolean("pref_shake_throw", false);
    if (throwOnShake)
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
}