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

时间:2015-09-08 20:00:18

标签: java android

我有两个程序(Accelerometer和Magnetometer)都使用传感器管理器。我认为问题是当我将这两个程序合并为一个来获取他们的数据时,onResume()在程序之间使用哪个Sensor Manager之间感到困惑。 如果我可以为同一个Class中的两个程序使用两个不同的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--------------------------------------------------------------
}

1 个答案:

答案 0 :(得分:0)

您可以使用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){
      ....
}