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.metinkale.prayerapp.compass.Main.java

@Override
protected void onResume() {
    super.onResume();
    mSensorManager.unregisterListener(mMagAccel);

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

    if (mSelCity == null) {
        mSelCity = (TextView) findViewById(R.id.selcity);
        mSelCity.setOnClickListener(new OnClickListener() {
            @Override/*  w  w  w  . j  ava  2s.c o m*/
            public void onClick(View arg0) {
                if (App.isOnline()) {
                    startActivity(new Intent(Main.this, LocationPicker.class));
                } else {
                    Toast.makeText(Main.this, R.string.noConnection, Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    if (PermissionUtils.get(this).pLocation) {
        LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        List<String> providers = locMan.getProviders(true);
        for (String provider : providers) {
            locMan.requestLocationUpdates(provider, 0, 0, this);
            Location lastKnownLocation = locMan.getLastKnownLocation(provider);
            if (lastKnownLocation != null) {
                calcQiblaAngel(lastKnownLocation);
            }
        }
    }

    if (Prefs.getCompassLat() != 0) {
        Location loc = new Location("custom");
        loc.setLatitude(Prefs.getCompassLat());
        loc.setLongitude(Prefs.getCompassLng());
        calcQiblaAngel(loc);
    }
}

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

private void createListView() {

    overviewList.clear();//from   w w w. j  a v  a2s.  c o m

    Overview overviewTitle = new Overview(getApplicationContext());
    overviewTitle.setSensorName("Nome Sensore");
    overviewTitle.setCurrentValue("Valore Corrente");
    overviewTitle.setValueSend("Valore Inviato");
    overviewList.add(overviewTitle);

    Overview overview0 = new Overview(getApplicationContext());
    overview0.setSensorName("Speed");
    overview0.setCurrentValue("" + mySensor.getCurrentSpeed());
    overview0.setValueSend(lastSpeedValue);
    overviewList.add(overview0);

    for (int k = 0; k < sensorList.size(); k++) {
        Overview overview = new Overview(getApplicationContext());
        switch (sensorList.get(k).getType()) {
        case Sensor.TYPE_AMBIENT_TEMPERATURE: // Gradi Celsius (C)
            overview.setSensorName("Temperature");
            overview.setCurrentValue("" + mySensor.getCurrentTemp());
            overview.setValueSend(lastTempValue);
            overviewList.add(overview);
            break;

        case Sensor.TYPE_PRESSURE:
            overview.setSensorName("Pressure");
            overview.setCurrentValue("" + mySensor.getCurrentPressure());
            overview.setValueSend(lastPressureValue);
            overviewList.add(overview);
            break;

        case Sensor.TYPE_LIGHT: // lx
            overview.setSensorName("Light");
            overview.setCurrentValue("" + mySensor.getCurrentLight());
            overview.setValueSend(lastLightValue);
            overviewList.add(overview);
            break;

        case Sensor.TYPE_ACCELEROMETER: // m/s2
            overview.setSensorName("Accelerometer");
            overview.setCurrentValue("" + mySensor.getCurrentAcceleration());
            overview.setValueSend(lastAccelerationValue);
            overviewList.add(overview);
            break;

        case Sensor.TYPE_GYROSCOPE: // rad/s
            overview.setSensorName("Gyroscope");
            overview.setCurrentValue("" + mySensor.getCurrentGyroscope());
            overview.setValueSend(lastGyroscopeValue);
            overviewList.add(overview);
            break;

        case Sensor.TYPE_MAGNETIC_FIELD: // T
            overview.setSensorName("Magnetic Field");
            overview.setCurrentValue("" + mySensor.getCurrentMagnetic());
            overview.setValueSend(lastMagneticValue);
            overviewList.add(overview);
            break;

        case Sensor.TYPE_PROXIMITY: // cm
            overview.setSensorName("Proximity");
            overview.setCurrentValue("" + mySensor.getCurrentProximity());
            overview.setValueSend(lastProximityValue);
            overviewList.add(overview);
            break;

        case Sensor.TYPE_ROTATION_VECTOR: // unita di misura sconosciuta
            overview.setSensorName("Rotation Vector");
            overview.setCurrentValue("" + mySensor.getCurrentRotation());
            overview.setValueSend(lastRotationValue);
            overviewList.add(overview);
            break;

        case Sensor.TYPE_GRAVITY: // m/s2
            overview.setSensorName("Gravity");
            overview.setCurrentValue("" + mySensor.getCurrentGravity());
            overview.setValueSend(lastGravityValue);
            overviewList.add(overview);
            break;

        case Sensor.TYPE_LINEAR_ACCELERATION: // m/s2
            overview.setSensorName("Linear Acceleration");
            overview.setCurrentValue("" + mySensor.getCurrentLinearAcceleration());
            overview.setValueSend(lastLinearAccelerationValue);
            overviewList.add(overview);
            break;

        case Sensor.TYPE_RELATIVE_HUMIDITY: // %
            overview.setSensorName("Relative Humidity");
            overview.setCurrentValue("" + mySensor.getCurrentHumidity());
            overview.setValueSend(lastRelativeHumidity);
            overviewList.add(overview);
            break;

        default:
            break;
        }
    }

    listView.setAdapter(new OverviewAdapter(getApplicationContext(), overviewList));

}

From source file:io.v.moments.ux.MainActivity.java

private void initializeShakeDetector() {
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}

From source file:com.example.lijingjiang.mobile_sensor_display.SimplePedometerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    /**//w ww. java 2s  .c  om
     * Initialization
     */
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (ActivityCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, 0);

    }

    /**
     * Attach UI objects
     */
    hrResultView = (TextView) findViewById(R.id.hr);
    hrResultView.setText(TEXT_HR + hr);

    distanceResultView = (TextView) findViewById(R.id.result_field);
    distanceResultView.setText(String.valueOf(accumulatedLocationCalculatedFromGoogle) + " Meters");

    stepsResultView = (TextView) findViewById(R.id.steps);
    stepsResultView.setText(TEXT_NUM_STEPS + numSteps);

    startButtonRunning = (Button) findViewById(R.id.start_running_button);
    stopButtonRunning = (Button) findViewById(R.id.stop_running_button);
    startButtonRunning.setEnabled(true);
    stopButtonRunning.setEnabled(false);

    startButtonExercising = (Button) findViewById(R.id.start_exercise_button);
    stopButtonExercising = (Button) findViewById(R.id.stop_exercise_button);
    startButtonExercising.setEnabled(true);
    stopButtonExercising.setEnabled(false);

    startButtonSleeping = (Button) findViewById(R.id.start_sleep_button);
    stopButtonSleeping = (Button) findViewById(R.id.stop_sleep_button);
    startButtonSleeping.setEnabled(true);
    stopButtonSleeping.setEnabled(false);

    ageField = (EditText) findViewById(R.id.age_field);
    exerciseTypeField = (EditText) findViewById(R.id.exercise_type);

    /**
     * Sensor initialization
     */
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    simpleStepDetector = new SimpleStepDetector();
    simpleStepDetector.registerListener(this);

    /**
     * Google Service Initialization
     */
    mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();

    mLocationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(2000) // 2000 milliseconds
            .setFastestInterval(2000); // 2000 milliseconds

    /**
     * The following code will enable the GPS sensor to get location data
     */
    //        locationManager = (LocationManager)
    //        this.getSystemService(Context.LOCATION_SERVICE);
    //        locationListener = new GPSLocationListener();
    //        locationProvider = LocationManager.GPS_PROVIDER;
    //        lastKnown =
    //        locationManager.getLastKnownLocation(locationProvider);
    //        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
    //        minTimeMs, minDistanceMeters, locationListener);

    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //distanceResultView.setText(R.string.zero);
            hrResultView.setText(TEXT_HR + hr);
            stepsResultView.setText(TEXT_NUM_STEPS + numSteps);
            //Start runnable here, maybe?
            mHandler.sendMessageDelayed(Message.obtain(), mUpdatePeriodMillis);
        }
    };

    mHandler.sendMessageDelayed(Message.obtain(), mUpdatePeriodMillis);

    Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
    bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}

From source file:radu.pidroid.Controller.java

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

    ActionBar actionBar = getActionBar();
    actionBar.hide();/* w  w  w . j  av a 2  s.c  o m*/

    speechButton = (ImageView) findViewById(R.id.speechButton);
    speechButton.setOnClickListener(new ImageView.OnClickListener() {
        public void onClick(View view) {
            startVoiceRecognition();
        } // onClick
    });

    touchControlsLayout = (RelativeLayout) findViewById(R.id.TouchControlsLayout);
    forwardsPowerImageView = (ImageView) findViewById(R.id.forwardsPowerImageView);
    forwardsPowerImageView.setOnTouchListener(this);
    backwardsPowerImageView = (ImageView) findViewById(R.id.backwardsPowerImageView);
    backwardsPowerImageView.setOnTouchListener(this);

    forwardsPowerProgressBar = (ProgressBar) findViewById(R.id.forwardsPowerProgressBar);
    backwardsPowerProgressBar = (ProgressBar) findViewById(R.id.backwardsPowerProgressBar);

    sliderControlsLayout = (RelativeLayout) findViewById(R.id.SliderControlsLayout);
    forwardsPowerSeekBar = (SeekBar) findViewById(R.id.forwardsPowerSeekBar);
    forwardsPowerSeekBar.setOnSeekBarChangeListener(this);
    backwardsPowerSeekBar = (SeekBar) findViewById(R.id.backwardsPowerSeekBar);
    backwardsPowerSeekBar.setOnSeekBarChangeListener(this);

    joystickControlsLayout = (RelativeLayout) findViewById(R.id.JoystickControlsLayout);
    largeCameraJoystickView = (JoystickView) findViewById(R.id.largeCameraJoystickView);
    largeCameraJoystickView.setMoveListener(this);
    directionJoystickView = (JoystickView) findViewById(R.id.directionJoystickView);
    directionJoystickView.setMoveListener(this);

    videoFeedMjpegView = (MjpegView) findViewById(R.id.videoFeedSurfaceView);
    hudImageView = (ImageView) findViewById(R.id.hudImageView);
    levelIndicatorImageView = (ImageView) findViewById(R.id.levelIndicatorImageView);

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mGeomagnetic = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

    smallCameraJoystickView = (JoystickView) findViewById(R.id.cameraJoystickView);
    smallCameraJoystickView.setMoveListener(this);
    smallCameraJoystickView.setTag("smallCamera");

    spinControlOn = false;
    toggleSpinImageView = (ImageView) findViewById(R.id.toggleSpinImageView);
    toggleSpinImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // if spinControl is ON then tiltControls are OFF and vice versa
            spinControlOn = !spinControlOn;
            tiltControlsOn = !tiltControlsOn;

            if (spinControlOn)
                toggleSpinImageView.setImageResource(R.drawable.spin_button_down);
            else
                toggleSpinImageView.setImageResource(R.drawable.spin_button_up);

            // Let PiDroid know whether to spin
            mMessenger.toggleSpin(spinControlOn);
        } // onClick
    });

    // Get the message from the intent
    Intent intent = getIntent();
    serverIP = intent.getStringExtra(Main.EXTRA_SERVERIP);
    serverPort = intent.getIntExtra(Main.EXTRA_SERVERPORT, 8090);

    mMessenger = new Messenger(this, serverIP, serverPort);
    mRecogniser = new CommandRecogniser(this, mMessenger, videoFeedMjpegView);

    if (Main.detailsCheckBox.isChecked())
        loadPreferences();
    else
        clearPreferences();

    setupNavigationDrawer();
    setupVideoFeed();

    if (tutorialsOn)
        new ControllerTutorial(this).start();
}

From source file:edu.cmu.android.restaurant.MapFragment.java

/**
 * //  w  ww  .java2 s.  c  om
 * Shaking: - User shake the mobile to find the coupon of the restaurant in
 * the detail fragment page - After shaking, the mobile vibrates for 500 ms
 * 
 * */
@Override
public void onSensorChanged(SensorEvent event) {

    int sensorType = event.sensor.getType();
    float[] values = event.values;

    if (sensorType == Sensor.TYPE_ACCELEROMETER) {
        if ((Math.abs(values[0]) > 15 || Math.abs(values[1]) > 15 || Math.abs(values[2]) > 15)) {

            Log.d("sensor ", "X- values[0] = " + values[0]);
            Log.d("sensor ", "Y- values[1] = " + values[1]);
            Log.d("sensor ", "Z- values[2] = " + values[2]);

            findDeal();
            dealDisplay();
            /* audio play */
            MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.coupon_audio);
            mp.seekTo(0);
            mp.start();
        }
    }
}

From source file:com.sitewhere.android.example.ExampleFragment.java

/**
 * Only schedule SiteWhere reporting thread once we have a connection to the server.
 *//*www . java 2 s  .  com*/
public void startDeviceMonitoring() {
    Log.d(TAG, "Starting device monitoring.");

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // Start location updates.
            boolean locationStarted = false;
            locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
            if (ActivityCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(getActivity(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "No permissions for location. Requesting permissions from user.");
                requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION }, LOCATION_REQUEST_CODE);
                return;
            }
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                        ExampleFragment.this);
                locationStarted = true;
                Log.d(TAG, "Started monitoring locations via GPS provider.");
            } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                        ExampleFragment.this);
                locationStarted = true;
                Log.d(TAG, "Started monitoring locations via network provider.");
            } else {
                locationStarted = false;
                Log.d(TAG, "No location provider available. Will not monitor location.");
            }

            // Start accelerometer updates.
            boolean accelerometerStarted = false;
            sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
                rotationVector = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
                sensorManager.registerListener(ExampleFragment.this, rotationVector,
                        SensorManager.SENSOR_DELAY_NORMAL);
                accelerometerStarted = true;
                Log.d(TAG, "Started monitoring accelerometer.");
            } else {
                Toast.makeText(getActivity().getApplicationContext(),
                        "Unable to start accelerometer updates. No accelerometer provided", Toast.LENGTH_LONG);
                accelerometerStarted = false;
                Log.d(TAG, "Unable to monitor accelerometer.");
            }

            // Send alerts to SiteWhere.
            SiteWhereMessageClient messageClient = SiteWhereMessageClient.getInstance();
            try {
                if (locationStarted)
                    messageClient.sendDeviceAlert(messageClient.getUniqueDeviceId(), "location.started",
                            "Started to read location data.", null);
            } catch (SiteWhereMessagingException ex) {
                Log.e(TAG, "Unable to send location.started alert to SiteWhere.");
            }
            try {
                if (accelerometerStarted)
                    messageClient.sendDeviceAlert(messageClient.getUniqueDeviceId(), "accelerometer.started",
                            "Started to read accelerometer data.", null);
            } catch (SiteWhereMessagingException e) {
                Log.e(TAG, "Unable to send accelerometer.started alert to SiteWhere.");
            }

            if (scheduler != null) {
                scheduler.shutdownNow();
            }
            scheduler = Executors.newSingleThreadScheduledExecutor();
            scheduler.scheduleAtFixedRate(new SiteWhereDataReporter(), SEND_INTERVAL_IN_SECONDS,
                    SEND_INTERVAL_IN_SECONDS, TimeUnit.SECONDS);
            Log.d(TAG, "Set up scheduler for monitoring.");
        }
    });
}

From source file:il.ac.shenkar.todos.view.MainActivity.java

@Override
protected void onResume() {
    super.onResume();
    // reopen database 
    taskListModel.getDataBase().open();/*from  w  ww .  j a va2 s.co  m*/
    // register sensors resources
    mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_UI);
    adapter.notifyDataSetChanged();
}

From source file:com.mhennessy.mapfly.MainActivity.java

@Override
public void onSensorChanged(SensorEvent event) {
    switch (event.sensor.getType()) {
    case Sensor.TYPE_ORIENTATION:
        onOrientationChange(event);/*from  ww  w .  j ava 2s  .c  om*/
        break;
    case Sensor.TYPE_ACCELEROMETER:
        onAccelerometerChange(event);
        break;
    }
}

From source file:com.android.camera2.its.ItsService.java

@Override
public void onCreate() {
    try {/*from   w w w . j a v a 2  s.  c om*/
        mThreadExitFlag = false;

        // Get handle to camera manager.
        mCameraManager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
        if (mCameraManager == null) {
            throw new ItsException("Failed to connect to camera manager");
        }
        mBlockingCameraManager = new BlockingCameraManager(mCameraManager);
        mCameraListener = new BlockingStateCallback();

        // Register for motion events.
        mEvents = new LinkedList<MySensorEvent>();
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mMagSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        mGyroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        mSensorManager.registerListener(this, mAccelSensor, SensorManager.SENSOR_DELAY_FASTEST);
        mSensorManager.registerListener(this, mMagSensor, SensorManager.SENSOR_DELAY_FASTEST);
        mSensorManager.registerListener(this, mGyroSensor, SensorManager.SENSOR_DELAY_FASTEST);

        // Get a handle to the system vibrator.
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

        // Create threads to receive images and save them.
        for (int i = 0; i < MAX_NUM_OUTPUT_SURFACES; i++) {
            mSaveThreads[i] = new HandlerThread("SaveThread" + i);
            mSaveThreads[i].start();
            mSaveHandlers[i] = new Handler(mSaveThreads[i].getLooper());
        }

        // Create a thread to handle object serialization.
        (new Thread(new SerializerRunnable())).start();
        ;

        // Create a thread to receive capture results and process them.
        mResultThread = new HandlerThread("ResultThread");
        mResultThread.start();
        mResultHandler = new Handler(mResultThread.getLooper());

        // Create a thread for the camera device.
        mCameraThread = new HandlerThread("ItsCameraThread");
        mCameraThread.start();
        mCameraHandler = new Handler(mCameraThread.getLooper());

        // Create a thread to process commands, listening on a TCP socket.
        mSocketRunnableObj = new SocketRunnable();
        (new Thread(mSocketRunnableObj)).start();
    } catch (ItsException e) {
        Logt.e(TAG, "Service failed to start: ", e);
    }
}