Example usage for android.hardware SensorManager SENSOR_DELAY_NORMAL

List of usage examples for android.hardware SensorManager SENSOR_DELAY_NORMAL

Introduction

In this page you can find the example usage for android.hardware SensorManager SENSOR_DELAY_NORMAL.

Prototype

int SENSOR_DELAY_NORMAL

To view the source code for android.hardware SensorManager SENSOR_DELAY_NORMAL.

Click Source Link

Document

rate (default) suitable for screen orientation changes

Usage

From source file:com.example.android.batchstepsensor.BatchStepSensorFragment.java

/**
 * Register a {@link android.hardware.SensorEventListener} for the sensor and max batch delay.
 * The maximum batch delay specifies the maximum duration in microseconds for which subsequent
 * sensor events can be temporarily stored by the sensor before they are delivered to the
 * registered SensorEventListener. A larger delay allows the system to handle sensor events more
 * efficiently, allowing the system to switch to a lower power state while the sensor is
 * capturing events. Once the max delay is reached, all stored events are delivered to the
 * registered listener. Note that this value only specifies the maximum delay, the listener may
 * receive events quicker. A delay of 0 disables batch mode and registers the listener in
 * continuous mode.//from w ww  . j  a va 2  s  .c o  m
 * The optimium batch delay depends on the application. For example, a delay of 5 seconds or
 * higher may be appropriate for an  application that does not update the UI in real time.
 *
 * @param maxdelay
 * @param sensorType
 */
private void registerEventListener(int maxdelay, int sensorType) {
    // BEGIN_INCLUDE(register)

    // Keep track of state so that the correct sensor type and batch delay can be set up when
    // the app is restored (for example on screen rotation).
    mMaxDelay = maxdelay;
    if (sensorType == Sensor.TYPE_STEP_COUNTER) {
        mState = STATE_COUNTER;
        /*
        Reset the initial step counter value, the first event received by the event listener is
        stored in mCounterSteps and used to calculate the total number of steps taken.
         */
        mCounterSteps = 0;
        Log.i(TAG, "Event listener for step counter sensor registered with a max delay of " + mMaxDelay);
    } else {
        mState = STATE_DETECTOR;
        Log.i(TAG, "Event listener for step detector sensor registered with a max delay of " + mMaxDelay);
    }

    // Get the default sensor for the sensor type from the SenorManager
    SensorManager sensorManager = (SensorManager) getActivity().getSystemService(Activity.SENSOR_SERVICE);
    // sensorType is either Sensor.TYPE_STEP_COUNTER or Sensor.TYPE_STEP_DETECTOR
    Sensor sensor = sensorManager.getDefaultSensor(sensorType);

    // Register the listener for this sensor in batch mode.
    // If the max delay is 0, events will be delivered in continuous mode without batching.
    final boolean batchMode = sensorManager.registerListener(mListener, sensor,
            SensorManager.SENSOR_DELAY_NORMAL, maxdelay);

    if (!batchMode) {
        // Batch mode could not be enabled, show a warning message and switch to continuous mode
        getCardStream().getCard(CARD_NOBATCHSUPPORT).setDescription(getString(R.string.warning_nobatching));
        getCardStream().showCard(CARD_NOBATCHSUPPORT);
        Log.w(TAG, "Could not register sensor listener in batch mode, " + "falling back to continuous mode.");
    }

    if (maxdelay > 0 && batchMode) {
        // Batch mode was enabled successfully, show a description card
        getCardStream().showCard(CARD_BATCHING_DESCRIPTION);
    }

    // Show the explanation card
    getCardStream().showCard(CARD_EXPLANATION);

    // END_INCLUDE(register)

}

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

/**
 * When the start button is pressed, execute this function
 *//*  ww  w.java  2 s. c  o m*/
public void startCollection_Running(View view) {

    /**
     * Get current time stamp to calculate the elapsed time
     */
    date = new Date();

    startButtonRunning.setEnabled(false);
    stopButtonRunning.setEnabled(true);

    startButtonExercising.setEnabled(false);
    stopButtonExercising.setEnabled(false);

    startButtonSleeping.setEnabled(false);
    stopButtonSleeping.setEnabled(false);

    /**
     * Reset all data
     */
    hr = 0;
    numSteps = 0;
    accumulatedLocationCalculatedFromGoogle = 0;
    startRecording = true;

    distanceResultView.setText(R.string.zero + " Meters");
    hrResultView.setText(TEXT_HR + hr);
    stepsResultView.setText(TEXT_NUM_STEPS + numSteps);

    /**
     * When click the start button, register the sensor and start google
     * location service
     */
    sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);

    /**
     * The following code blocks is required by google api
     */
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        // TODO: Add function logic when user don't give the permission
        return;
    }
    previousLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    currentLatitude = previousLocation.getLatitude();
    currentLongitude = previousLocation.getLongitude();

    /**
     * The following toast will indicate that the user has provided the permission,
     * and the app can get the location information now
     */
    //Toast
    //       .makeText(this, currentLatitude + " WORKS " + currentLongitude + "",
    //                Toast.LENGTH_LONG)
    //       .show();

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

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);
}

From source file:kr.ac.kpu.wheeling.blackbox.Camera2VideoFragment.java

@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
    mTextureView = (AutoFitTextureView) view.findViewById(kr.ac.kpu.wheeling.R.id.texture);
    //-------------------------------------------
    tracker_layout = (LinearLayout) view.findViewById(R.id.tracker_layout);
    mButtonVisible = (Button) view.findViewById(R.id.btn_visible);
    mButtonVisible.setOnClickListener(this);
    mButtonRiding = (Button) view.findViewById(R.id.btn_visible_riding);
    mButtonRiding.setOnClickListener(this);
    btn_btest = (Button) view.findViewById(R.id.btn_btest);
    btn_btest.setOnClickListener(this);
    sqLiteHandler = new SQLiteHandler(getActivity());
    //----------------------------------------------
    mButtonVideo = (Button) view.findViewById(kr.ac.kpu.wheeling.R.id.video);
    mButtonVideo.setOnClickListener(this);

    mButtonSetting = (Button) view.findViewById(kr.ac.kpu.wheeling.R.id.interval);
    mButtonSetting.setOnClickListener(this);
    //view.findViewById(R.id.info).setOnClickListener(this);
    chronometer = (Chronometer) view.findViewById(kr.ac.kpu.wheeling.R.id.chronometer);

    sensorManager.registerListener(gyroListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    mButtonGallery = (Button) view.findViewById(kr.ac.kpu.wheeling.R.id.menu);
    mButtonGallery.setOnClickListener(this);
    galleryActivity = new Intent(getActivity(), GalleryActivity.class);

    chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
        @Override//from  www .java2 s .c  o m
        public void onChronometerTick(Chronometer chronometer) {
            if ((int) (((SystemClock.elapsedRealtime() - chronometer.getBase()))) > 10500) {
                try {
                    stopRecordingVideo();
                    mIsSensorChanged = false;
                } catch (Exception e) {

                }
                chronometer.stop();
            }
        }
    });
}

From source file:org.mixare.MixViewActivity.java

/**
 * Part of Android LifeCycle that gets called when "MixViewActivity" resumes.
 * <br/>// ww  w. ja v  a 2 s.  c  om
 * Does:
 * - Acquire Screen Lock
 * - Refreshes Data and Downloads
 * - Initiate four Matrixes that holds user's rotation markerRenderer.
 * - Re-register Sensors. {@link android.hardware.SensorManager SensorManager}
 * - Re-register Location Manager. {@link org.mixare.mgr.location.LocationFinder LocationFinder}
 * - Switch on Download Thread. {@link org.mixare.mgr.downloader.DownloadManager DownloadManager}
 * - restart markerRenderer refresh Timer.
 * <br/>
 * {@inheritDoc}
 */
@Override
protected void onResume() {
    super.onResume();
    if (cubeView != null) {
        //mRenderer.start();
        cubeView.onResume();
    }
    mSensorManager.registerListener(cubeView, mOrienation, SensorManager.SENSOR_DELAY_NORMAL);

    try {
        killOnError();
        MixContext.setActualMixViewActivity(this);
        HttpTools.setContext(MixContext.getInstance());

        //repaint(); //repaint when requested
        getMarkerRenderer().doStart();
        getMarkerRenderer().clearEvents();
        MixContext.getInstance().getNotificationManager().setEnabled(true);
        refreshDownload();

        MixContext.getInstance().getDataSourceManager().refreshDataSources();

        float angleX, angleY;

        int marker_orientation = -90;

        int rotation = Compatibility.getRotation(this);

        // display text from left to right and keep it horizontal
        angleX = (float) Math.toRadians(marker_orientation);
        getMixViewData().getM1().set(1f, 0f, 0f, 0f, (float) Math.cos(angleX), (float) -Math.sin(angleX), 0f,
                (float) Math.sin(angleX), (float) Math.cos(angleX));
        angleX = (float) Math.toRadians(marker_orientation);
        angleY = (float) Math.toRadians(marker_orientation);
        if (rotation == 1) {
            getMixViewData().getM2().set(1f, 0f, 0f, 0f, (float) Math.cos(angleX), (float) -Math.sin(angleX),
                    0f, (float) Math.sin(angleX), (float) Math.cos(angleX));
            getMixViewData().getM3().set((float) Math.cos(angleY), 0f, (float) Math.sin(angleY), 0f, 1f, 0f,
                    (float) -Math.sin(angleY), 0f, (float) Math.cos(angleY));
        } else {
            getMixViewData().getM2().set((float) Math.cos(angleX), 0f, (float) Math.sin(angleX), 0f, 1f, 0f,
                    (float) -Math.sin(angleX), 0f, (float) Math.cos(angleX));
            getMixViewData().getM3().set(1f, 0f, 0f, 0f, (float) Math.cos(angleY), (float) -Math.sin(angleY),
                    0f, (float) Math.sin(angleY), (float) Math.cos(angleY));

        }

        getMixViewData().getM4().toIdentity();

        for (int i = 0; i < getMixViewData().getHistR().length; i++) {
            getMixViewData().getHistR()[i] = new Matrix();
        }

        getMixViewData()
                .addListSensors(getMixViewData().getSensorMgr().getSensorList(Sensor.TYPE_ACCELEROMETER));
        if (getMixViewData().getSensor(0).getType() == Sensor.TYPE_ACCELEROMETER) {
            getMixViewData().setSensorGrav(getMixViewData().getSensor(0));
        } //else report error (unsupported hardware)

        getMixViewData()
                .addListSensors(getMixViewData().getSensorMgr().getSensorList(Sensor.TYPE_MAGNETIC_FIELD));
        if (getMixViewData().getSensor(1).getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            getMixViewData().setSensorMag(getMixViewData().getSensor(1));
        } //else report error (unsupported hardware)

        if (!getMixViewData().getSensorMgr().getSensorList(Sensor.TYPE_GYROSCOPE).isEmpty()) {
            getMixViewData()
                    .addListSensors(getMixViewData().getSensorMgr().getSensorList(Sensor.TYPE_GYROSCOPE));
            if (getMixViewData().getSensor(2).getType() == Sensor.TYPE_GYROSCOPE) {
                getMixViewData().setSensorGyro(getMixViewData().getSensor(2));
            }
            getMixViewData().getSensorMgr().registerListener(this, getMixViewData().getSensorGyro(),
                    SENSOR_DELAY_GAME);
        }

        getMixViewData().getSensorMgr().registerListener(this, getMixViewData().getSensorGrav(),
                SENSOR_DELAY_GAME);
        getMixViewData().getSensorMgr().registerListener(this, getMixViewData().getSensorMag(),
                SENSOR_DELAY_GAME);

        try {
            GeomagneticField gmf = MixContext.getInstance().getLocationFinder().getGeomagneticField();
            angleY = (float) Math.toRadians(-gmf.getDeclination());
            getMixViewData().getM4().set((float) Math.cos(angleY), 0f, (float) Math.sin(angleY), 0f, 1f, 0f,
                    (float) -Math.sin(angleY), 0f, (float) Math.cos(angleY));
        } catch (Exception ex) {
            doError(ex, GPS_ERROR);
        }

        if (!isNetworkAvailable()) {
            Log.d(Config.TAG, "no network");
            doError(null, NO_NETWORK_ERROR);
        } else {
            Log.d(Config.TAG, "network");
        }

        MixContext.getInstance().getDownloadManager().switchOn();
        MixContext.getInstance().getLocationFinder().switchOn();
    } catch (Exception ex) {
        doError(ex, GENERAL_ERROR);
        try {
            if (getMixViewData().getSensorMgr() != null) {
                getMixViewData().getSensorMgr().unregisterListener(this, getMixViewData().getSensorGrav());
                getMixViewData().getSensorMgr().unregisterListener(this, getMixViewData().getSensorMag());
                getMixViewData().getSensorMgr().unregisterListener(this, getMixViewData().getSensorGyro());
                getMixViewData().setSensorMgr(null);
            }

            if (MixContext.getInstance() != null) {
                MixContext.getInstance().getLocationFinder().switchOff();
                MixContext.getInstance().getDownloadManager().switchOff();
            }
        } catch (Exception ignore) {
        }
    } finally {
        //This does not conflict with registered sensors (sensorMag, sensorGrav)
        //This is a place holder to API returned listed of sensors, we registered
        //what we need, the rest is unnecessary.
        getMixViewData().clearAllSensors();
    }

    Log.d(Config.TAG, "resume");
    if (getMarkerRenderer() == null) {
        return;
    }
    if (getMarkerRenderer().isFrozen() && getMixViewData().getSearchNotificationTxt() == null) {
        getMixViewData().setSearchNotificationTxt(new TextView(this));
        getMixViewData().getSearchNotificationTxt().setWidth(getPaintScreen().getWidth());
        getMixViewData().getSearchNotificationTxt().setPadding(10, 2, 0, 0);
        getMixViewData().getSearchNotificationTxt().setText(getString(R.string.search_active_1) + " "
                + DataSourceList.getDataSourcesStringList() + getString(R.string.search_active_2));
        ;
        getMixViewData().getSearchNotificationTxt().setBackgroundColor(Color.DKGRAY);
        getMixViewData().getSearchNotificationTxt().setTextColor(Color.WHITE);

        getMixViewData().getSearchNotificationTxt().setOnTouchListener(this);
        addContentView(getMixViewData().getSearchNotificationTxt(),
                new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    } else if (!getMarkerRenderer().isFrozen() && getMixViewData().getSearchNotificationTxt() != null) {
        getMixViewData().getSearchNotificationTxt().setVisibility(View.GONE);
        getMixViewData().setSearchNotificationTxt(null);
    }
}

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

public void startCollection_Exercising(View view) {

    /**/*from w ww . j  a v  a  2  s  . com*/
     * Get current time stamp to calculate the elapsed time
     */
    date = new Date();

    startButtonExercising.setEnabled(false);
    stopButtonExercising.setEnabled(true);

    startButtonRunning.setEnabled(false);
    stopButtonRunning.setEnabled(false);

    startButtonSleeping.setEnabled(false);
    stopButtonSleeping.setEnabled(false);

    /**
     * Reset all data
     */
    hr = 0;
    numSteps = 0;
    accumulatedLocationCalculatedFromGoogle = 0;
    startRecording = true;

    distanceResultView.setText(R.string.zero + " Meters");
    hrResultView.setText(TEXT_HR + hr);
    stepsResultView.setText(TEXT_NUM_STEPS + numSteps);

    /**
     * When click the start button, register the sensor and start google
     * location service
     */
    sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);

    /**
     * The following code blocks is required by google api
     */
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        // TODO: Add function logic when user don't give the permission
        return;
    }
    previousLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    currentLatitude = previousLocation.getLatitude();
    currentLongitude = previousLocation.getLongitude();

    /**
     * The following toast will indicate that the user has provided the permission,
     * and the app can get the location information now
     */
    //Toast
    //       .makeText(this, currentLatitude + " WORKS " + currentLongitude + "",
    //                Toast.LENGTH_LONG)
    //       .show();

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

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

@Override
public void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    logState("onResume");
}

From source file:tv.piratemedia.flightcontroller.BluetoothComputerFragment.java

public void setupAtimiter() {
    SensorManager mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    List<Sensor> sensors = mSensorManager.getSensorList(Sensor.TYPE_PRESSURE);
    SensorEventListener sensorListener = new SensorEventListener() {
        @Override/*  w  w  w  .  ja va 2s. co m*/
        public void onSensorChanged(SensorEvent event) {
            if (currentPreasure > event.values[0] - 0.5 || currentPreasure < event.values[0] + 0.5) {
                currentPreasure = event.values[0];
                currentAltitude = SensorManager.getAltitude(SensorManager.PRESSURE_STANDARD_ATMOSPHERE,
                        currentPreasure);

                JSONObject msg = new JSONObject();
                try {
                    msg.put("action", "altitude_update");
                    msg.put("value", currentAltitude);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sendTextMessage(msg.toString());
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };
    if (sensors.size() > 0) {
        sensor = sensors.get(0);
        mSensorManager.registerListener(sensorListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    } else {

    }
}

From source file:tw.example.robert.myapplication.bluetoothchat.BluetoothChatFragment.java

protected void SetSensor() {
    List sensors = sensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
    //??/*from   w w  w  . ja  va  2s. com*/
    if (sensors.size() > 0) {
        //registerListener?implements SensorEventListener
        //SensorEventListeneronAccuracyChangedonSensorChanged
        //
        sensorManager.registerListener(this, (Sensor) sensors.get(0), SensorManager.SENSOR_DELAY_NORMAL);
    }
}

From source file:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java

/**
 * Device Orientation Profile<br>/*w  ww. j  ava 2s . c o  m*/
 * ?.
 * 
 * @param response ?
 * @param deviceId ?ID
 * @param sessionKey 
 */
public void registerDeviceOrientationEvent(final Intent response, final String deviceId,
        final String sessionKey) {

    mDeviceId = deviceId;
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    List<Sensor> sensors = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);

    if (sensors.size() > 0) {
        Sensor sensor = sensors.get(0);
        mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    sensors = mSensorManager.getSensorList(Sensor.TYPE_GYROSCOPE);

    if (sensors.size() > 0) {
        Sensor sensor = sensors.get(0);
        mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.RESULT_OK);
    response.putExtra(DConnectMessage.EXTRA_VALUE, "Register OnDeviceOrientation event");
    sendBroadcast(response);
}