Example usage for android.hardware SensorManager SENSOR_DELAY_UI

List of usage examples for android.hardware SensorManager SENSOR_DELAY_UI

Introduction

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

Prototype

int SENSOR_DELAY_UI

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

Click Source Link

Document

rate suitable for the user interface

Usage

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

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

    final long newCount = Note.count(Note.class);

    if (newCount > initialCount) {
        // A note is added
        Log.d("Main", "Adding new note");

        // Just load the last added note (new)
        Note note = Note.last(Note.class);

        notes.add(note);/*ww w .  j  ava  2 s. co m*/
        adapter.notifyItemInserted((int) newCount);

        initialCount = newCount;
    }

    if (modifyPos != -1) {
        notes.set(modifyPos, Note.listAll(Note.class).get(modifyPos));
        adapter.notifyItemChanged(modifyPos);
    }
    if (hasAccelerometer) {
        // Register the Session Manager Listener onResume
        mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
    }

}

From source file:net.line2soft.preambul.views.SlippyMapActivity.java

/**
 * Init map's overlays (compass, buttons, ...), attach listener.
 * You can launch map on normal or edit mode (to pick a position).
 * @param addFavorite If true, edit mode (to add favorite), if false normal mode
 *///  ww  w  .  j av  a2  s . co  m
private void initMap(boolean addFavorite) {
    if (addFavorite == false) {
        //Launch map in normal mode
        findViewById(R.id.list_item).setVisibility(View.VISIBLE);
        findViewById(R.id.drawer).setVisibility(View.VISIBLE);

        //Add listener on excursions button
        ImageButton btExcursionsImg = (ImageButton) findViewById(R.id.imageButton1);
        btExcursionsImg.setOnClickListener(listener);
        btExcursionsImg.setVisibility(View.VISIBLE);
        findViewById(R.id.excursionButton).setVisibility(View.VISIBLE);
        ((ImageButton) findViewById(R.id.imageRight)).setOnClickListener(listener);
        ((ImageButton) findViewById(R.id.imageLeft)).setOnClickListener(listener);
        ((ImageButton) findViewById(R.id.favoritesButton)).setOnClickListener(listener);

        //Display POIs on map
        try {
            PointOfInterest[] pois = MapController.getInstance(this).getCurrentLocation().getPOIs(this);
            Drawable icon = null;
            OverlayItem item = null;
            boolean displayPoiType = true;
            for (PointOfInterest poi : pois) {
                displayPoiType = PreferenceManager.getDefaultSharedPreferences(this)
                        .getBoolean("type" + poi.getType().getId(), true);
                if (displayPoiType) {
                    icon = (poi.getType().getIcon() == null) ? poi.getType().getCategory().getIcon()
                            : poi.getType().getIcon();
                    item = new OverlayItem(poi.getPoint(), poi.getName(), poi.getComment(),
                            BalloonItemizedOverlay.boundLeftCenter(icon));
                    overlayPoiItemMarker.addItem(item, poi);
                }
            }
        } catch (Exception e) {
            displayInfo(getString(R.string.message_map_poi_load_error));
            e.printStackTrace();
        }

        //Display favorites on map
        try {
            HashMap<String, NamedPoint> favorites = MapController.getInstance(this).getCurrentLocation()
                    .getNamedFavorites(this);
            Drawable icon = getResources().getDrawable(R.drawable.marker_favorite);
            OverlayItem item = null;
            for (NamedPoint favPoint : favorites.values()) {
                item = new OverlayItem(favPoint.getPoint(), favPoint.getName(), favPoint.getComment(),
                        BalloonItemizedOverlay.boundLeftCenter(icon));
                overlayPoiItemMarker.addItem(item, favPoint);
            }
        } catch (IOException e) {
            displayInfo(getString(R.string.message_map_favorite_load_error));
            e.printStackTrace();
        }

        //Display excursions and instruction on map
        int pathToDisplay = MapController.getInstance(this).getPathToDisplay();
        displayExcursion(pathToDisplay);
        int instructionToDisplay = MapController.getInstance(this).getInstructionToDisplay() - 1;
        //Set instruction, only if > 0 because if instruction=0, was set when displaying excursion
        if (instructionToDisplay > 0) {
            setNavigationInstructionToDisplay(instructionToDisplay);
        }
        //Display of the bookmarksButton
        boolean displaybookmarksButton = PreferenceManager.getDefaultSharedPreferences(this)
                .getBoolean("displayBookmarksButton", true);
        ImageButton img = (ImageButton) findViewById(R.id.favoritesButton);
        if (displaybookmarksButton) {
            img.setVisibility(View.VISIBLE);
        } else {
            img.setVisibility(View.GONE);
        }
        //Display point
        GeoPoint pointToDisplay = MapController.getInstance(this).getPointToDisplay();
        if (pointToDisplay != null) {
            displayPosition(pointToDisplay.getLatitude(), pointToDisplay.getLongitude());
            MapController.getInstance(this).setPointToDisplay(null);
        }
        //Launch compass
        boolean displayCompass = PreferenceManager.getDefaultSharedPreferences(this)
                .getBoolean("displayCompass", true);
        CompassView cpv = (CompassView) findViewById(R.id.compass);
        CompassView cpvBig = (CompassView) findViewById(R.id.compassBig);
        if (displayCompass) {
            SensorManager mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            Sensor mAccelerometer = mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            Sensor mField = mySensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
            if (mField != null && mAccelerometer != null) {
                mySensorManager.registerListener(listener, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
                mySensorManager.registerListener(listener, mField, SensorManager.SENSOR_DELAY_UI);
                cpv.setOnClickListener(listener);
                if (isCompassAccurate) {
                    cpv.setVisibility(View.VISIBLE);
                } else {
                    displayInfo(getString(R.string.message_compass_not_accurate));
                    cpv.setVisibility(View.GONE);
                }
                cpvBig.setVisibility(View.GONE);
                cpvBig.setOnClickListener(listener);
            } else {
                cpv.setVisibility(View.GONE);
                cpvBig.setVisibility(View.GONE);
            }
        } else {
            cpv.setVisibility(View.GONE);
            cpvBig.setVisibility(View.GONE);
        }

        //Hide validate button
        findViewById(R.id.validatePositionButton).setVisibility(View.GONE);
        findViewById(R.id.imageViewValidate).setVisibility(View.GONE);
        findViewById(R.id.mapPointer).setVisibility(View.GONE);
    } else {
        //Launch map in edit mode, to set coordinates of a favorite
        findViewById(R.id.list_item).setVisibility(View.GONE);
        findViewById(R.id.compass).setVisibility(View.GONE);
        findViewById(R.id.drawer).setVisibility(View.GONE);
        findViewById(R.id.favoritesButton).setVisibility(View.GONE);

        findViewById(R.id.mapPointer).setVisibility(View.VISIBLE);

        //Display validate button and add listener
        findViewById(R.id.validatePositionButton).setVisibility(View.VISIBLE);
        findViewById(R.id.imageViewValidate).setVisibility(View.VISIBLE);
        findViewById(R.id.imageViewValidate).setOnClickListener(listener);

        this.addFavorite = false;
    }
}

From source file:org.akvo.caddisfly.sensor.colorimetry.liquid.ColorimetryLiquidActivity.java

private void startTest() {

    mResults = new ArrayList<>();

    mWaitingForStillness = false;/*from   w  ww  . ja  v  a  2s  .  co  m*/
    mIsFirstResult = true;

    mShakeDetector.setMinShakeAcceleration(1);
    mShakeDetector.setMaxShakeDuration(MAX_SHAKE_DURATION_2);
    mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);

    (new AsyncTask<Void, Void, Void>() {

        @Nullable
        @Override
        protected Void doInBackground(Void... params) {
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            mCameraFragment = CameraDialogFragment.newInstance();

            mCameraFragment.setPictureTakenObserver(new CameraDialogFragment.PictureTaken() {
                @Override
                public void onPictureTaken(@NonNull byte[] bytes, boolean completed) {
                    Bitmap bitmap = ImageUtil.getBitmap(bytes);

                    Display display = getWindowManager().getDefaultDisplay();
                    int rotation;
                    switch (display.getRotation()) {
                    case Surface.ROTATION_0:
                        rotation = DEGREES_90;
                        break;
                    case Surface.ROTATION_180:
                        rotation = DEGREES_270;
                        break;
                    case Surface.ROTATION_270:
                        rotation = DEGREES_180;
                        break;
                    case Surface.ROTATION_90:
                    default:
                        rotation = 0;
                        break;
                    }

                    bitmap = ImageUtil.rotateImage(bitmap, rotation);

                    TestInfo testInfo = CaddisflyApp.getApp().getCurrentTestInfo();

                    Bitmap croppedBitmap;

                    if (testInfo.isUseGrayScale()) {
                        croppedBitmap = ImageUtil.getCroppedBitmap(bitmap,
                                ColorimetryLiquidConfig.SAMPLE_CROP_LENGTH_DEFAULT, false);

                        if (croppedBitmap != null) {
                            croppedBitmap = ImageUtil.getGrayscale(croppedBitmap);
                        }
                    } else {
                        croppedBitmap = ImageUtil.getCroppedBitmap(bitmap,
                                ColorimetryLiquidConfig.SAMPLE_CROP_LENGTH_DEFAULT, true);
                    }

                    //Ignore the first result as camera may not have focused correctly
                    if (!mIsFirstResult) {
                        if (croppedBitmap != null) {
                            getAnalyzedResult(croppedBitmap);
                        } else {
                            showError(
                                    String.format(TWO_SENTENCE_FORMAT, getString(R.string.chamberNotFound),
                                            getString(R.string.checkChamberPlacement)),
                                    ImageUtil.getBitmap(bytes));
                            mCameraFragment.stopCamera();
                            mCameraFragment.dismiss();
                            return;
                        }
                    }
                    mIsFirstResult = false;

                    if (completed) {
                        analyzeFinalResult(bytes, croppedBitmap);
                        mCameraFragment.dismiss();
                    } else {
                        sound.playShortResource(R.raw.beep);
                    }
                }
            });

            acquireWakeLock();

            delayRunnable = new Runnable() {
                @Override
                public void run() {
                    final FragmentTransaction ft = getFragmentManager().beginTransaction();
                    Fragment prev = getFragmentManager().findFragmentByTag("cameraDialog");
                    if (prev != null) {
                        ft.remove(prev);
                    }
                    ft.addToBackStack(null);
                    try {
                        mCameraFragment.show(ft, "cameraDialog");
                        mCameraFragment.takePictures(AppPreferences.getSamplingTimes(),
                                ColorimetryLiquidConfig.DELAY_BETWEEN_SAMPLING);
                    } catch (Exception e) {
                        Timber.e(e);
                        finish();
                    }
                }
            };

            delayHandler.postDelayed(delayRunnable, ColorimetryLiquidConfig.DELAY_BETWEEN_SAMPLING);

        }
    }).execute();
}

From source file:com.coincide.alphafitness.ui.Fragment_Main.java

@Override
public void onResume() {
    super.onResume();
    //        getActivity().getActionBar().setDisplayHomeAsUpEnabled(false);

    Database db = Database.getInstance(getActivity());

    if (BuildConfig.DEBUG)
        db.logState();/*w ww .ja v  a  2  s  .  c  o m*/
    // read todays offset
    todayOffset = db.getSteps(Util.getToday());

    SharedPreferences prefs = getActivity().getSharedPreferences("pedometer", Context.MODE_PRIVATE);

    goal = prefs.getInt("goal", Fragment_Settings.DEFAULT_GOAL);
    since_boot = db.getCurrentSteps(); // do not use the value from the sharedPreferences
    int pauseDifference = since_boot - prefs.getInt("pauseCount", since_boot);

    // register a sensorlistener to live update the UI if a step is taken
    if (!prefs.contains("pauseCount")) {
        SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        if (sensor == null) {
            new AlertDialog.Builder(getActivity()).setTitle(R.string.no_sensor)
                    .setMessage(R.string.no_sensor_explain)
                    .setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(final DialogInterface dialogInterface) {
                            getActivity().finish();
                        }
                    }).setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(final DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    }).create().show();
        } else {
            sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI, 0);
        }
    }

    since_boot -= pauseDifference;

    total_start = db.getTotalWithoutToday();
    total_days = db.getDays();

    db.close();

    SharedPreferences sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES,
            Context.MODE_PRIVATE);
    mBodyWeight = Float.parseFloat(sharedpreferences.getString(sp_weight, "0"));

    stepsDistanceChanged();

}

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

@Override
public void onResume() {
    super.onResume();
    instance = this;

    Log.d(TAG, "resume");

    ControllableResourceInitializerService.startResourceLoading(getApplicationContext(), "lang_support_codes",
            "lang_support_names", "lang_support_urls");
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    mapper.addNotificationListener(this);

    if (KeypadMapperApplication.getInstance().getSettings().isCompassAvailable()) {
        sensorManager.registerListener(this, gsensor, SensorManager.SENSOR_DELAY_UI);
        sensorManager.registerListener(this, msensor, SensorManager.SENSOR_DELAY_UI);
    }/*www  .j  av a 2 s .  com*/

    locationProvider.addLocationListener(this);
    mapper.onResume();
    menu.onResume();
    satelliteInfo.onResume();

    String languageToLoad = KeypadMapperApplication.getInstance().getSettings().getCurrentLanguageCode();
    if (!lang.equals(languageToLoad) || uiOptimizationEnabled != KeypadMapperApplication.getInstance()
            .getSettings().isLayoutOptimizationEnabled()) {
        Intent localIntent = new Intent(this, KeypadMapper2Activity.class);
        Bundle data = new Bundle();
        data.putInt("state", state.ordinal());
        data.putBoolean("extended_address", extendedAddressActive);
        data.putBoolean("sat_info", satteliteInfoVisible);
        localIntent.putExtras(data);
        startActivity(localIntent);
        finish();
    } else {
        updateLocale();
    }

    if (!locationProvider.isLocationServiceEnabled()) {
        showDialogGpsDisabled();
    } else if (gpsDialog != null) {
        gpsDialog.dismiss();
        gpsDialog = null;
    }

    if (KeypadMapperApplication.getInstance().getSettings().isLayoutOptimizationEnabled()) {
        // show empty toast so that there's no problem with showing
        // optimized view. On some phones with Android 2.3 and maybe others,
        // layout isn't rendered in fullscreen and showing toast fixes it.
        View etv = getLayoutInflater().inflate(R.layout.empty_toast_view, null);
        Toast t = new Toast(getApplicationContext());
        t.setView(etv);
        t.setDuration(1);
        t.show();
    }

    RateMeActivity.startRateMe(this);
}

From source file:itcr.gitsnes.MainActivity.java

/** Called after onRestoreInstanceState(Bundle),
 * onRestart(), or onPause(), for your activity
 * to start interacting with the user */
@Override//from   w  w  w .  ja  v a2s .co  m
public void onResume() {
    super.onResume();
    // uiHelper.onResume();
    mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}

From source file:com.coincide.alphafitness.ui.Fragment_Main.java

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_split_count:
        Dialog_Split.getDialog(getActivity(), total_start + Math.max(todayOffset + since_boot, 0)).show();
        return true;
    case R.id.action_pause:
        SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
        Drawable d;/* w  w  w .  jav a 2  s .co m*/
        if (getActivity().getSharedPreferences("pedometer", Context.MODE_PRIVATE).contains("pauseCount")) { // currently paused -> now resumed
            sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER),
                    SensorManager.SENSOR_DELAY_UI, 0);
            item.setTitle(R.string.pause);
            d = getResources().getDrawable(R.drawable.ic_pause);
        } else {
            sm.unregisterListener(this);
            item.setTitle(R.string.resume);
            d = getResources().getDrawable(R.drawable.ic_resume);
        }
        d.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
        item.setIcon(d);
        getActivity().startService(new Intent(getActivity(), SensorListener.class).putExtra("action",
                SensorListener.ACTION_PAUSE));
        return true;
    default:
        return ((Activity_Main) getActivity()).optionsItemSelected(item);
    }
}

From source file:com.example.zoetablet.BasicFragmentActivity.java

@Override
protected void onResume() {

    Log.i("Tablet", "Resume...");

    //Compass Activity 
    Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    Sensor magField = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    sensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_UI);
    sensorManager.registerListener(sensorEventListener, magField, SensorManager.SENSOR_DELAY_UI);

    super.onResume();
}

From source file:mp.teardrop.PlaybackService.java

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

From source file:com.coincide.alphafitness.ui.Fragment_Main.java

public void onSWatchStart() {
    if (isButtonStartPressed) {
        onSWatchStop();/*from   ww w .  j a v a2s.co m*/
        //            startStopService();

        try {
            SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            sm.unregisterListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {

        //            startStopService();
        getActivity().startService(new Intent(getActivity(), SensorListener.class));

        try {
            SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER),
                    SensorManager.SENSOR_DELAY_UI, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

        isButtonStartPressed = true;

        startButton.setBackgroundResource(R.drawable.btn_stop_states);
        startButton.setText(R.string.btn_stop);

        getActivity().startService(new Intent(getActivity(), BroadcastService.class));

        /*lapButton.setBackgroundResource(R.drawable.btn_lap_states);
        lapButton.setText(R.string.btn_lap);
        lapButton.setEnabled(true);*/

        //            setUpNotification();

        /*timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {
                    currentTime += 1;
        //                            lapTime += 1;
                
                   *//*manager = (NotificationManager)
                             getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
                              
                      // update notification text
                      builder.setContentText(TimeFormatUtil.toDisplayString(currentTime));
                      manager.notify(mId, builder.build());*//*
                                                                      
                                                              // update ui
                                                              tv_duration.setText(TimeFormatUtil.toDisplayString(currentTime));
                                                              }
                                                              });
                                                              }
                                                              }, 0, 100);*/
    }
}