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.bolatu.gezkoncsvlogger.GyroOrientation.GyroscopeOrientation.java

/**
 * Reinitialize the sensor and filter./*w  w w  . j a  v a 2  s . c o m*/
 */
public void reset() {
    // copy the new gyro values into the gyro array
    // convert the raw gyro data into a rotation vector
    deltaVGyroscope = new double[4];

    vOrientation = new float[3];
    qvOrientation = new float[4];

    // rotation matrix from gyro data
    rmGyroscope = new float[9];

    qGyroscopeDelta = null;
    qGyroscope = null;

    isOrientationValidAccelMag = false;

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

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

From source file:galilei.kelimekavanozu.activity.ThemeChooserActivity.java

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

    // Accelerometer check
    PackageManager manager = getPackageManager();
    hasAccelerometer = manager.hasSystemFeature(PackageManager.FEATURE_SENSOR_ACCELEROMETER);

    setContentView(R.layout.activity_theme_chooser);
    SugarContext.init(this);
    arkaplan500 = (ImageView) findViewById(R.id.arkaplan500);
    kavanoz = (ImageView) findViewById(R.id.cannonball_logo);
    recyclerView = (RecyclerView) findViewById(R.id.main_list);

    final Animation shake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake);

    fab = (FloatingActionButton) findViewById(R.id.fab);

    StaggeredGridLayoutManager gridLayoutManager = new StaggeredGridLayoutManager(2,
            StaggeredGridLayoutManager.VERTICAL);
    gridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);

    recyclerView.setLayoutManager(gridLayoutManager);
    initialCount = Note.count(Note.class);
    if (savedInstanceState != null)
        modifyPos = savedInstanceState.getInt("modify");

    if (initialCount >= 0) {

        notes = Note.listAll(Note.class);

        adapter = new KelimelerAdapter(ThemeChooserActivity.this, notes);
        recyclerView.setAdapter(adapter);

    }/*from   w ww .  j a  va2  s  .  c  o m*/

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {

        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.ic_add_24dp);
        drawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTint(drawable, Color.WHITE);
        DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_IN);

        fab.setImageDrawable(drawable);

    }

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //                Crashlytics.log("Yeni Kelime: butona basld");
            //                Answers.getInstance().logCustom(new CustomEvent("Ekle butonuna basld"));
            Intent i = new Intent(ThemeChooserActivity.this, AddNoteActivity.class);
            startActivity(i);

        }
    });
    if (isNetworkConnected()) {
        new arkaplan().execute();
    }
    // Handling swipe to delete

    setUpViews();
    ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0,
            ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            //Remove swiped item from list and notify the RecyclerView

            final int position = viewHolder.getAdapterPosition();
            final Note note = notes.get(viewHolder.getAdapterPosition());
            notes.remove(viewHolder.getAdapterPosition());
            adapter.notifyItemRemoved(position);

            note.delete();
            initialCount -= 1;

            Snackbar.make(fab, "Kelime silindi", Snackbar.LENGTH_SHORT)
                    .setAction("GER AL", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            note.save();
                            notes.add(position, note);
                            adapter.notifyItemInserted(position);
                            initialCount += 1;

                        }
                    }).show();
        }

    };

    ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
    itemTouchHelper.attachToRecyclerView(recyclerView);
    adapter.SetOnItemClickListener(new KelimelerAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {

            Log.d("Main", "click");

            Intent i = new Intent(ThemeChooserActivity.this, AddNoteActivity.class);
            i.putExtra("isEditing", true);
            i.putExtra("note_title", notes.get(position).title);
            i.putExtra("note", notes.get(position).note);
            i.putExtra("note_time", notes.get(position).time);

            modifyPos = position;

            startActivity(i);
        }
    });
    if (hasAccelerometer) {
        kavanoz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // View element to be shaken
                // Perform animation
                if (notclick) {
                    kavanoz.startAnimation(shake);
                    shakemode = true;
                    notclick = false;
                    Snackbar.make(fab, "Rastgele kelimelerden birini grmek iin telefonunuzu sallayn.",
                            Snackbar.LENGTH_LONG).show();
                    kavanoz.setColorFilter(Color.argb(100, 255, 140, 0));
                } else {
                    shakemode = false;
                    notclick = true;
                    kavanoz.setColorFilter(getResources().getColor(R.color.green));

                }
            }
        });
        // ShakeDetector initialization
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mShakeDetector = new ShakeDetector();

        mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() {

            @Override
            public void onShake(int count) {
                if (shakemode) {
                    /*
                     * The following method, "handleShakeEvent(count):" is a stub //
                    * method you would use to setup whatever you want done once the
                    * device has been shook.
                    */
                    // View element to be shaken
                    // Perform animation
                    Crashlytics.log("Shake event : triggered");
                    Answers.getInstance().logCustom(new CustomEvent("Shake event : tetiklendi"));
                    kavanoz.startAnimation(shake);
                    new rastgeletweet().execute();
                }
            }
        });
    }
}

From source file:gov.nasa.arc.geocam.geocam.CameraActivity.java

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

    mServiceBound = bindService(new Intent(this, GeoCamService.class), mServiceConn, Context.BIND_AUTO_CREATE);
    if (!mServiceBound) {
        Log.e(GeoCamMobile.DEBUG_ID, "CameraActivity::onResume - error binding to service");
    }// w  ww .  j a v  a2s .  c  om

    mForeground.foreground();

    mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_GAME);
    mSensorManager.registerListener(mSensorListener,
            mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_GAME);

    mLatText.setText("Lat: unavailable");
    mLonText.setText("Lon: unavailable");

    IntentFilter filter = new IntentFilter(GeoCamMobile.LOCATION_CHANGED);
    this.registerReceiver(mLocationReceiver, filter);

    if (getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
        showDialog(DIALOG_HIDE_KEYBOARD);
    }

    // Unset focus and picture status flags when returning from another activity
    mLensIsFocused = false;
    mPictureTaken = false;
}

From source file:com.vonglasow.michael.satstat.SensorSectionFragment.java

/**
 * Called by {@link MainActivity} when a sensor's reading changes. Updates sensor display.
 *//*  w ww. j  a  v  a  2 s  .  c  o m*/
public void onSensorChanged(SensorEvent event) {
    switch (event.sensor.getType()) {
    case Sensor.TYPE_ACCELEROMETER:
        accX.setText(String.format("%." + mAccSensorRes + "f", event.values[0]));
        accY.setText(String.format("%." + mAccSensorRes + "f", event.values[1]));
        accZ.setText(String.format("%." + mAccSensorRes + "f", event.values[2]));
        accTotal.setText(String.format("%." + mAccSensorRes + "f", Math.sqrt(
                Math.pow(event.values[0], 2) + Math.pow(event.values[1], 2) + Math.pow(event.values[2], 2))));
        accStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
        break;
    case Sensor.TYPE_ORIENTATION:
        orAzimuth.setText(String.format("%.0f%s", event.values[0], getString(R.string.unit_degree)));
        orAziText.setText(MainActivity.formatOrientation(this.getContext(), event.values[0]));
        orPitch.setText(String.format("%.0f%s", event.values[1], getString(R.string.unit_degree)));
        orRoll.setText(String.format("%.0f%s", event.values[2], getString(R.string.unit_degree)));
        orStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
        break;
    case Sensor.TYPE_GYROSCOPE:
        rotX.setText(String.format("%." + mGyroSensorRes + "f", event.values[0]));
        rotY.setText(String.format("%." + mGyroSensorRes + "f", event.values[1]));
        rotZ.setText(String.format("%." + mGyroSensorRes + "f", event.values[2]));
        rotTotal.setText(String.format("%." + mGyroSensorRes + "f", Math.sqrt(
                Math.pow(event.values[0], 2) + Math.pow(event.values[1], 2) + Math.pow(event.values[2], 2))));
        rotStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
        break;
    case Sensor.TYPE_MAGNETIC_FIELD:
        magX.setText(String.format("%." + mMagSensorRes + "f", event.values[0]));
        magY.setText(String.format("%." + mMagSensorRes + "f", event.values[1]));
        magZ.setText(String.format("%." + mMagSensorRes + "f", event.values[2]));
        magTotal.setText(String.format("%." + mMagSensorRes + "f", Math.sqrt(
                Math.pow(event.values[0], 2) + Math.pow(event.values[1], 2) + Math.pow(event.values[2], 2))));
        magStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
        break;
    case Sensor.TYPE_LIGHT:
        light.setText(String.format("%." + mLightSensorRes + "f", event.values[0]));
        lightStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
        break;
    case Sensor.TYPE_PROXIMITY:
        proximity.setText(String.format("%." + mProximitySensorRes + "f", event.values[0]));
        proximityStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
        break;
    case Sensor.TYPE_PRESSURE:
        metPressure.setText(String.format("%." + mPressureSensorRes + "f", event.values[0]));
        pressureStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
        break;
    case Sensor.TYPE_RELATIVE_HUMIDITY:
        metHumid.setText(String.format("%." + mHumiditySensorRes + "f", event.values[0]));
        humidStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
        break;
    case Sensor.TYPE_AMBIENT_TEMPERATURE:
        metTemp.setText(String.format("%." + mTempSensorRes + "f", event.values[0]));
        tempStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
        break;
    }
}

From source file:com.sir_m2x.messenger.activities.ChatWindowPager.java

@Override
protected void onResume() {
    isActive = true;//from  w  ww  . j  a  v  a  2 s. c o  m
    registerReceiver(this.listener, new IntentFilter(MessengerService.INTENT_IS_TYPING));
    registerReceiver(this.listener, new IntentFilter(MessengerService.INTENT_NEW_IM));
    registerReceiver(this.listener, new IntentFilter(MessengerService.INTENT_DESTROY));
    registerReceiver(this.listener, new IntentFilter(MessengerService.INTENT_BUZZ));

    this.sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
    this.mAccel = 0.00f;
    this.mAccelCurrent = SensorManager.GRAVITY_EARTH;
    this.mAccelLast = SensorManager.GRAVITY_EARTH;

    if (Preferences.shake2Buzz)
        this.sensorMgr.registerListener(this, this.sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_UI);

    super.onResume();
}

From source file:com.richwareham.android.logallthethings.Camera2VideoFragment.java

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

    mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this)
            .addApi(LocationServices.API).build();

    mLocationRequest = new LocationRequest();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(5000);/*  w  w w .  j a  va  2  s  .com*/

    mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    int sensor_types[] = { Sensor.TYPE_ACCELEROMETER, Sensor.TYPE_GYROSCOPE, Sensor.TYPE_MAGNETIC_FIELD, };

    mSensors = new ArrayList<Sensor>();
    for (int type : sensor_types) {
        Sensor s = mSensorManager.getDefaultSensor(type);
        if (s == null) {
            continue;
        }
        mSensors.add(s);
    }
}

From source file:net.line2soft.preambul.controllers.SlippyMapListener.java

@Override
public void onSensorChanged(SensorEvent event) {
    CompassView cp = (CompassView) activity.findViewById(R.id.compass);
    CompassView cpBig = (CompassView) activity.findViewById(R.id.compassBig);
    switch (event.sensor.getType()) {
    case Sensor.TYPE_ACCELEROMETER:
        System.arraycopy(event.values, 0, mGravity, 0, 3);
        break;//from   w  ww  . jav  a2  s.c  o m
    case Sensor.TYPE_MAGNETIC_FIELD:
        System.arraycopy(event.values, 0, mMagnetic, 0, 3);
        break;
    default:
        return;
    }
    if (SensorManager.getRotationMatrix(mRotationM, null, mGravity, mMagnetic)) {
        SensorManager.remapCoordinateSystem(mRotationM, SensorManager.AXIS_X, SensorManager.AXIS_Z,
                mRemapedRotationM);
        SensorManager.getOrientation(mRemapedRotationM, mOrientation);
        int mAzimuth = (int) Math.round((Math.toDegrees(mOrientation[0])) * 2) / 2;
        cp.updateDirection(mAzimuth);
        cpBig.updateDirection(mAzimuth);
    }
}

From source file:com.tritop.androsense2.fragments.GpsFragment.java

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        mAccel = event.values;/*from   w w  w  .  jav  a2 s.c  o  m*/
    }
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        mMag = event.values;
    }
    if ((mAccel != null) && (mMag != null)) {
        float R[] = new float[9];
        float I[] = new float[9];
        float Rot[] = new float[9];
        if (SensorManager.getRotationMatrix(R, I, mAccel, mMag)) {
            float orientation[] = new float[3];
            int axisX = 0, axisY = 0;
            switch (display.getRotation()) {
            case Surface.ROTATION_0:
                axisX = SensorManager.AXIS_X;
                axisY = SensorManager.AXIS_Y;
                break;
            case Surface.ROTATION_90:
                axisX = SensorManager.AXIS_Y;
                axisY = SensorManager.AXIS_MINUS_X;
                break;
            case Surface.ROTATION_180:
                axisX = SensorManager.AXIS_MINUS_X;
                axisY = SensorManager.AXIS_MINUS_Y;
                break;
            case Surface.ROTATION_270:
                axisX = SensorManager.AXIS_MINUS_Y;
                axisY = SensorManager.AXIS_X;
                break;
            default:
                break;
            }

            SensorManager.remapCoordinateSystem(R, axisX, axisY, Rot);
            SensorManager.getOrientation(Rot, orientation);
            aRotation = orientation[0];
            aRotation = (int) Math.toDegrees(aRotation);
            satView.setAzimutRotation(-aRotation);
            satView.invalidate();
        }
    }
}

From source file:com.google.android.apps.santatracker.dasherdancer.DasherDancerActivity.java

@Override
public void onResume() {
    super.onResume();
    SensorManager manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    Sensor accel = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    manager.registerListener(this, accel, SensorManager.SENSOR_DELAY_NORMAL);
    mDetector.start(manager);/*from   w ww  . j ava  2s  .c o  m*/

    if (mInitialized) {
        //Start the animation for the first character.
        mPager.postDelayed(new Runnable() {

            @Override
            public void run() {
                loadAnimation(true, sCharacters[mPager.getCurrentItem()].getDuration(Character.ANIM_IDLE),
                        sCharacters[mPager.getCurrentItem()].getFrameIndices(Character.ANIM_IDLE),
                        sCharacters[mPager.getCurrentItem()].getFrames(Character.ANIM_IDLE));
            }

        }, 300);
    } else {
        if (mLoadAllBitmapsTask != null) {
            mLoadAllBitmapsTask.cancel(true);
        }
        mLoadAllBitmapsTask = new LoadAllBitmapsTask();
        mLoadAllBitmapsTask.execute(sCharacters[mPager.getCurrentItem()]);
    }
}

From source file:org.osm.keypadmapper2.KeypadMapper2Activity.java

/** Called when the activity is first created. */
@Override//from   w w w. j a  v  a 2  s  . c o  m
public void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "create");

    if (KeypadMapperApplication.getInstance().getSettings().isLayoutOptimizationEnabled()) {

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        uiOptimizationEnabled = true;
    }

    super.onCreate(savedInstanceState);

    if (KeypadMapperApplication.getInstance().getSettings().isCompassAvailable()) {
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        gsensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        msensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    }

    updateLocale();

    setContentView(R.layout.main);

    menu = new KeypadMapperMenu(findViewById(R.id.menu));
    menu.setMenuListener(this);

    gestureDetector = new GestureDetector(this, new MyGestureDetector());

    // check for external storage
    String extStorageState = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
        // We can read and write the media
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
        // We can only read the media
        showDialogFatalError(localizer.getString("errorStorageRO"));
    } else {
        // Something else is wrong. It may be one of many other states, but
        // all we need to know is we can neither read nor write
        showDialogFatalError(localizer.getString("errorStorageUnavailable"));
    }

    File kpmFolder = KeypadMapperApplication.getInstance().getKeypadMapperDirectory();
    if (!kpmFolder.exists()) {
        if (!kpmFolder.mkdir()) {
            showDialogFatalError(localizer.getString("FolderCreationFailed"));
        }
    }

    if (savedInstanceState == null) {
        savedInstanceState = getIntent().getExtras();
    }

    duplicates = new StringBuffer();
    allData = new StringBuffer();

    if (savedInstanceState == null) {
        // first start
        state = State.keypad;

        // only on first run automatically start GPS recording
        if (KeypadMapperApplication.getInstance().getSettings().isFirstRun()) {
            KeypadMapperApplication.getInstance().getSettings().clearFirstRun();
            KeypadMapperApplication.getInstance().startGpsRecording(); // always start when app starts
        }
    } else {
        // restart
        state = State.values()[savedInstanceState.getInt("state", State.keypad.ordinal())];
        satteliteInfoVisible = savedInstanceState.getBoolean("sat_info");

        extendedAddressActive = savedInstanceState.getBoolean("extended_address");

        if (savedInstanceState.getBoolean("debug_dialog_on")) {
            duplicates.append(savedInstanceState.getString("duplicates"));
            allData.append(savedInstanceState.getString("allData"));
            showTestScreenDialog();
        }
    }

    keypadFragment = (KeypadFragment) getSupportFragmentManager().findFragmentByTag("keypad");

    Log.d("Keypad", "isTablet = " + getResources().getBoolean(R.bool.is_tablet));
    if (!getResources().getBoolean(R.bool.is_tablet)) {
        extendedAddressFragment = (ExtendedAddressFragment) getSupportFragmentManager()
                .findFragmentByTag("extended_address");
    } else {
        extendedAddressFragment = (ExtendedAddressFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fragment_extended_address_tablet);
    }

    Log.d("Keypad", "extended address fragment = " + extendedAddressFragment);

    satelliteInfo = (SatelliteInfoFragment) getSupportFragmentManager().findFragmentByTag("satellite");

    satInfoView = findViewById(R.id.satellite_view);
    extendedAddressView = findViewById(R.id.extended_address_view);
    keypadView = findViewById(R.id.keypad_view);
    if (keypadView == null && extendedAddressView == null) {
        state = State.both;
    }

    btnTestVersion = (Button) keypadView.findViewById(R.id.btnTestVersion);
    /*
    btnTestVersion.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent i = new Intent();
        i.setClass(KeypadMapper2Activity.this, SettingsActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        startActivity(i);
                
        // show debug screen with all registered addresses and locations
        //showTestScreenDialog();
    }
    });*/

    if (satteliteInfoVisible) {
        showSatteliteInfo();
    } else {
        showKeypad();
    }

    locationProvider.refreshReferenceToGps();
}