Example usage for android.hardware SensorManager registerListener

List of usage examples for android.hardware SensorManager registerListener

Introduction

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

Prototype

public boolean registerListener(SensorEventListener listener, Sensor sensor, int samplingPeriodUs,
        Handler handler) 

Source Link

Document

Registers a android.hardware.SensorEventListener SensorEventListener for the given sensor.

Usage

From source file:ngoc.com.pedometer.ui.Fragment_Overview.java

private void startCountOrPause() {
    SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    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);//w  w w.j  a v a  2 s.  co m
    } else {
        sm.unregisterListener(this);
    }
    getActivity().startService(
            new Intent(getActivity(), SensorListener.class).putExtra("action", SensorListener.ACTION_PAUSE));
}

From source file:io.github.msc42.masterthemaze.GameActivity.java

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

    if (mGameThread != null) {
        mGameThread.restart();/*from   ww w .  j av a2s  . c  o  m*/
    }

    if (mMotion) {
        if (mSpeed > 0) {
            mAddCurrentDirectionToQueueThread = new AddCurrentDirectionToQueueThread(mMotionQueue,
                    mCurrentMoveDirection, mSpeed);
            mAddCurrentDirectionToQueueThread.start();
        }

        SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mAccelerometerEventListener = new AccelerometerEventListener(mRotation, mSensitivity,
                mCurrentMoveDirection, mMotionQueue);

        sensorManager.registerListener(mAccelerometerEventListener, accelerometer,
                SensorManager.SENSOR_DELAY_GAME, mSensorHandler);
    }

    if (mMotion) {
        mMotionDescriptionTextView.setText(R.string.connecting);
    } else {
        mTouchDescriptionTextView.setText(R.string.connecting);
        mUpButton.setVisibility(View.INVISIBLE);
        mRightButton.setVisibility(View.INVISIBLE);
        mDownButton.setVisibility(View.INVISIBLE);
        mLeftButton.setVisibility(View.INVISIBLE);
    }
}

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 w  w  .j av a 2s.co 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.coincide.alphafitness.ui.Fragment_Main.java

public void startStopService() {
    SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);

    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);/* ww  w .  j  a  v  a  2 s .c  o  m*/

    } else {
        sm.unregisterListener(this);

    }

    sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER), SensorManager.SENSOR_DELAY_UI, 0);

    getActivity().startService(new Intent(getActivity(), SensorListener.class));
    //.putExtra("action", SensorListener.ACTION_PAUSE));
}

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;//from   ww w  . j a  v  a  2  s  .c  o 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.coincide.alphafitness.ui.Fragment_Main.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    //        final View v = inflater.inflate(R.layout.fragment_overview, null);
    View v = null;//w w  w .  j a v  a  2  s .  c  o  m

    v = inflater.inflate(R.layout.fragment_main, container, false);

    //        stepsView = (TextView) v.findViewById(R.id.steps);
    //        totalView = (TextView) v.findViewById(R.id.total);
    totalView = (TextView) v.findViewById(R.id.tv_distance);
    tv_avg = (TextView) v.findViewById(R.id.tv_avg);
    tv_max = (TextView) v.findViewById(R.id.tv_max);
    tv_min = (TextView) v.findViewById(R.id.tv_min);
    //        averageView = (TextView) v.findViewById(R.id.average);

    /*
            pg = (PieChart) v.findViewById(R.id.graph);
            
            // slice for the steps taken today
            sliceCurrent = new PieModel("", 0, Color.parseColor("#99CC00"));
            pg.addPieSlice(sliceCurrent);
            
            // slice for the "missing" steps until reaching the goal
            sliceGoal = new PieModel("", Fragment_Settings.DEFAULT_GOAL, Color.parseColor("#CC0000"));
            pg.addPieSlice(sliceGoal);
            
            pg.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(final View view) {
        showSteps = !showSteps;
        stepsDistanceChanged();
    }
            });
            
            pg.setDrawValueInPie(false);
            pg.setUsePieRotation(true);
            pg.startAnimation();
    */

    /*
    * MainActivity
    * */
    // Always cast your custom Toolbar here, and set it as the ActionBar.
    Toolbar tb = (Toolbar) v.findViewById(R.id.toolbar);
    ((AppCompatActivity) getActivity()).setSupportActionBar(tb);

    TextView tv_tb_center = (TextView) tb.findViewById(R.id.tv_tb_center);
    tv_tb_center.setText("ALPHA FITNESS");

    /*   ImageButton imgbtn_cart = (ImageButton) tb.findViewById(R.id.imgbtn_cart);
       imgbtn_cart.setVisibility(View.GONE);*/

    tb.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getActivity().onBackPressed();
        }
    });

    // Get the ActionBar here to configure the way it behaves.
    final ActionBar ab = ((AppCompatActivity) getActivity()).getSupportActionBar();
    //ab.setHomeAsUpIndicator(R.drawable.ic_menu); // set a custom icon for the default home button
    ab.setDisplayShowHomeEnabled(false); // show or hide the default home button
    ab.setDisplayHomeAsUpEnabled(false);
    ab.setDisplayShowCustomEnabled(false); // enable overriding the default toolbar layout
    ab.setDisplayShowTitleEnabled(false); // disable the default title element here (for centered title)

    tv_duration = (TextView) v.findViewById(R.id.tv_duration);

    startButton = (Button) v.findViewById(R.id.btn_start);
    if (isButtonStartPressed) {
        startButton.setBackgroundResource(R.drawable.btn_stop_states);
        startButton.setText(R.string.btn_stop);
        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();
        }

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

    startButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            onSWatchStart();
        }
    });
    iv_profile = (ImageView) v.findViewById(R.id.iv_profile);
    iv_profile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Database db = Database.getInstance(getActivity());
            tot_workouts = db.getTotWorkouts();
            tot_workTime = db.getWorkTime();
            Log.e("Tot Work time", tot_workTime + "");
            //                int seconds = (int) (tot_workTime / 1000) % 60;
            //                int minutes = (int) ((tot_workTime / (1000 * 60)) % 60);

            long millis = tot_workTime * 100; // obtained from StopWatch
            long hours = (millis / 1000) / 3600;
            long minutes = (millis / 1000) / 60;
            long seconds = (millis / 1000) % 60;

            db.close();

            Intent i = new Intent(getActivity(), ProfileActivity.class);
            i.putExtra("avg_distance", avg_distance + "");
            i.putExtra("all_distance", all_distance + "");
            i.putExtra("avg_time", tv_duration.getText().toString());
            i.putExtra("all_time", tv_duration.getText().toString());
            i.putExtra("avg_calories", avg_calories + "");
            i.putExtra("all_calories", all_calories + "");
            i.putExtra("tot_workouts", tot_workouts + "");
            i.putExtra("avg_workouts", tot_workouts + "");

            i.putExtra("tot_workTime", hours + " hrs " + minutes + " min " + seconds + " sec");

            startActivity(i);

        }
    });

    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getBaseContext());

    if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode);
        dialog.show();

    } else { // Google Play Services are available

        // Initializing
        mMarkerPoints = new ArrayList<LatLng>();

        // Getting reference to SupportMapFragment of the activity_main
        //            SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
        MapFragment fm = (MapFragment) getActivity().getFragmentManager().findFragmentById(R.id.map);

        // Getting Map for the SupportMapFragment
        mGoogleMap = fm.getMap();

        // Enable MyLocation Button in the Map
        mGoogleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location From GPS
        Location location;
        if (provider != null) {

            if (ActivityCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(getActivity(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return null;
            }
            location = locationManager.getLastKnownLocation(provider);
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        } else {
            location = new Location("");
            location.setLatitude(0.0d);//your coords of course
            location.setLongitude(0.0d);
        }

        if (location != null) {
            onLocationChanged(location);
        }

        // Setting onclick event listener for the map
        mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {

                // Already map contain destination location
                if (mMarkerPoints.size() > 1) {

                    FragmentManager fm = getActivity().getSupportFragmentManager();
                    mMarkerPoints.clear();
                    mGoogleMap.clear();
                    LatLng startPoint = new LatLng(mLatitude, mLongitude);
                    drawMarker(startPoint);
                }

                drawMarker(point);

                // Checks, whether start and end locations are captured
                if (mMarkerPoints.size() >= 2) {
                    LatLng origin = mMarkerPoints.get(0);
                    LatLng dest = mMarkerPoints.get(1);

                    // Getting URL to the Google Directions API
                    String url = getDirectionsUrl(origin, dest);

                    DownloadTask downloadTask = new DownloadTask();

                    // Start downloading json data from Google Directions API
                    downloadTask.execute(url);
                }
            }
        });
        fixedCentreoption = new MarkerOptions();

        mGoogleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {

            @Override
            public void onCameraChange(CameraPosition position) {
                // TODO Auto-generated method stub
                // Get the center of the Map.

                mGoogleMap.clear();

                LatLng centerOfMap = mGoogleMap.getCameraPosition().target;

                // Update your Marker's position to the center of the Map.
                fixedCentreoption.position(centerOfMap);
                //                   mGoogleMap.addMarker(fixedCentreoption);
                //                   drawMarker(centerOfMap);
                LatLng origin = new LatLng(0.0d, 0.0d);
                ;
                if (mMarkerPoints.size() > 0) {
                    origin = mMarkerPoints.get(0);
                }
                //                  LatLng dest = mMarkerPoints.get(1);
                LatLng dest = centerOfMap;
                // Getting URL to the Google Directions API
                String url = getDirectionsUrl(origin, dest);

                DownloadTask downloadTask = new DownloadTask();

                // Start downloading json data from Google Directions API
                downloadTask.execute(url);

                GPSTracker gpsTracker = new GPSTracker(getActivity().getApplicationContext());
                //               String Addrs = gpsTracker.location();
                Addrs = gpsTracker.locationBasedOnLatlng(centerOfMap);
                //               Toast.makeText(getApplicationContext(), Addrs, Toast.LENGTH_LONG).show();

            }
        });
    }

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

    return v;
}

From source file:ngoc.com.pedometer.ui.Fragment_Overview.java

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

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

    if (BuildConfig.DEBUG)
        db.logState();/*w  w  w  . j  a v  a2  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();

    stepsDistanceChanged();
}

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

public void onSWatchStart() {
    if (isButtonStartPressed) {
        onSWatchStop();/*ww  w. ja  v  a  2 s.c  o  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);*/
    }
}

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();/*from   ww w  .j  a v  a  2s . 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();

}