繁体   English   中英

如何在同一Java类中将两个传感器管理器用于加速度计和磁力计

[英]How to use Two Sensor Manager for Accelerometer and Magnetometer in the same Java class

我有两个使用Sensor Manager的程序(加速度计和磁力计)。 我认为问题在于,当我将这两个程序合并为一个程序以获取其数据时,在程序之间使用哪个Sensor Manager之间,onResume()变得令人困惑。 请告诉我是否可以对同一类中的两个程序使用两个不同的requestListener。 代码在下面,请参阅OnResume()方法。

@Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        mToolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(mToolbar);
        //Accelerometer--------------------------------------------------
        initializeViews();
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
            // success! we have an accelerometer
            accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            sensorManager.registerListener( this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
            vibrateThreshold = accelerometer.getMaximumRange() / 2;
        } else {

            // fail we dont have an accelerometer!
        }

        //initialize vibration
        v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        //----------------------------------------------------------------
        //Magnetometer------------------------------------------------------
        uT = (TextView) findViewById(R.id.textView2);
        max = (TextView) findViewById(R.id.textView3);
        min = (TextView) findViewById(R.id.textView4);
        // Get an instance of the sensor service
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mMagnetometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);


        PackageManager PM = this.getPackageManager();
        boolean gyro = PM.hasSystemFeature(PackageManager.FEATURE_SENSOR_GYROSCOPE);
        boolean light = PM.hasSystemFeature(PackageManager.FEATURE_SENSOR_LIGHT);


        if (gyro) {

            if (light) {
                Toast.makeText(getApplicationContext(), "Both light and gyroscope sensors are present", Toast.LENGTH_LONG).show();
            } else
                Toast.makeText(getApplicationContext(), "Only gyroscope sensor is present", Toast.LENGTH_LONG).show();

        }
        //-----------------------------------------------------------------------------------

    }
    //Accelerometer-----------------------------------------------------------

    private void initializeViews() {
        currentX = (TextView) findViewById(R.id.currentX);
        currentY = (TextView) findViewById(R.id.currentY);
        currentZ = (TextView) findViewById(R.id.currentZ);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_first, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        if (id == R.id.home_button){
            startActivity(new Intent(this, MainActivity.class));
        }

        return super.onOptionsItemSelected(item);
    }

    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        mSensorManager.registerListener(this, mMagnetometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }


    //onPause() unregister the accelerometer for stop listening the events

    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener( this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        // clean current values


        // display the current x,y,z accelerometer values

        // display the max x,y,z accelerometer values
        displayMaxValues();


        // get the change of the x,y,z values of the accelerometer

        deltaXX = Math.abs(lastX - event.values[0]);
        deltaX= deltaXX/2;
        deltaYY = Math.abs(lastY - event.values[1]);
        deltaY = deltaYY/2;
        deltaZZ = Math.abs(lastZ - event.values[2]);
        deltaZ= deltaZZ/2;

        // if the change is below 2, it is just plain noise

        if (deltaX < 2)
            deltaX = 0;
        if (deltaY < 2)
            deltaY = 0;
        if ((deltaX > vibrateThreshold) || (deltaY > vibrateThreshold) || (deltaZ > vibrateThreshold)) {
            v.vibrate(1);
        }
        //Magnetometer--------------------------------------------------
            float angularXSpeed = event.values[0];
            DecimalFormat decimalFormatuT = new DecimalFormat("00.00");
            Double CurrentuT = Double.parseDouble(decimalFormatuT.format(angularXSpeed));

            if (angularXSpeed > max1) {
                max1 = angularXSpeed;
                DecimalFormat decimalFormatMaxMag = new DecimalFormat("00.00");
                Double MaxMag = Double.parseDouble(decimalFormatMaxMag.format(max1));
                max.setText("Max " + "" + MaxMag);
            } else if (angularXSpeed < min1) {
                min1 = angularXSpeed;
                DecimalFormat decimalFormatMinMag = new DecimalFormat("00.00");
                Double MinMag = Double.parseDouble(decimalFormatMinMag.format(min1));
                min.setText("Min " + "" + MinMag);
            }

        //------------------------------------------------------------

    }

    private void displayMaxValues() {



        if (deltaX > deltaXMax) {
            deltaXMax = deltaX;
            maxX = (TextView) findViewById(R.id.maxX);
            DecimalFormat decimalFormat = new DecimalFormat("00.00");
            Double MaxXX = Double.parseDouble(decimalFormat.format(deltaXMax));
            maxX.setText(Double.toString(MaxXX));

        }

        if (deltaY > deltaYMax) {
            deltaYMax = deltaY;
            maxY = (TextView) findViewById(R.id.maxY);
            DecimalFormat decimalFormat = new DecimalFormat("00.00");
            Double MaxYY = Double.parseDouble(decimalFormat.format(deltaYMax));
            maxY.setText(Double.toString(MaxYY));

        }

        if (deltaZ > deltaZMax) {
            deltaZMax = deltaZ;
            maxZ = (TextView) findViewById(R.id.maxZ);
            DecimalFormat decimalFormat = new DecimalFormat("00.00");
            Double MaxZZ = Double.parseDouble(decimalFormat.format(deltaZMax));
            maxZ.setText(Double.toString(MaxZZ));


        }

    }




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

    }
    //Accelerometer--------------------------------------------------------------
}

您可以使用SensorManager实例访问设备上的所有传感器。 只需按以下方式修改您的代码,然后仅按以下方式将注册调用到onResume中:

protected void onCreate(Bundle savedInstanceState) {
  ....
  mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
  if ((accelerometer  = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null ) {...}
  if ((magnetometer   = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null ) {...}
  ....
}
// register the sensors only one time within onResume not in onCreate
@Override
protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
    mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_UI);
  }

另外,您还必须在方法onSensorChanged中检查传感器类型,如下所示:

onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
      ....
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD){
      ....
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM