android开发:传感器操作的实例

text1 = (TextView)findViewById(R.id.text1);//方向传感器
text2 = (TextView)findViewById(R.id.text2);//磁场传感器
text3 = (TextView)findViewById(R.id.text3);//温度传感器
text4 = (TextView)findViewById(R.id.text4);//光感传感器
text5 = (TextView)findViewById(R.id.text5);//压力传感器

mSensor = (SensorManager) getSystemService(SENSOR_SERVICE); //获取Sensor的服务对象

然后在onResume中注册需要开发的传感器监听,代码:
@Override
protected void onResume() {
    super.onResume();

    //注册方向
    mSensor.registerListener(
            this,
            mSensor.getDefaultSensor(Sensor.TYPE_ORIENTATION),
            SensorManager.SENSOR_DELAY_GAME
    );

    //注册磁场
    mSensor.registerListener(
            this,
            mSensor.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
            SensorManager.SENSOR_DELAY_GAME
    );

    //注册温度
    mSensor.registerListener(
            this,
            mSensor.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE),
            SensorManager.SENSOR_DELAY_GAME
    );

    //注册光度
    mSensor.registerListener(
            this,
            mSensor.getDefaultSensor(Sensor.TYPE_LIGHT),
            SensorManager.SENSOR_DELAY_GAME
    );

    //注册压力
    mSensor.registerListener(
            this,
            mSensor.getDefaultSensor(Sensor.TYPE_PRESSURE),
            SensorManager.SENSOR_DELAY_GAME
    );

监听时间的代码操作:

@Override
public void onSensorChanged(SensorEvent sensorEvent) {


    float[] val = sensorEvent.values;

    int SensorType = sensorEvent.sensor.getType();

    StringBuilder sb = null;

    switch (SensorType){
        case Sensor.TYPE_ORIENTATION:
            sb = new StringBuilder();
            sb.append("方向传感器:\nz:");
            sb.append(val[0]);
            sb.append(" \nX:");
            sb.append(val[1]);
            sb.append(" \nY:");
            sb.append(val[2]);
            text1.setText(sb.toString());
            break;
        case Sensor.TYPE_MAGNETIC_FIELD:
            sb = new StringBuilder();
            sb.append("磁场传感器:\nX:");
            sb.append(val[0]);
            sb.append(" \nY:");
            sb.append(val[1]);
            sb.append(" \nZ:");
            sb.append(val[2]);
            text2.setText(sb.toString());
            break;
        case Sensor.TYPE_AMBIENT_TEMPERATURE:
            sb = new StringBuilder();
            sb.append("温度传感器:\n当前温度是:");
            sb.append(val[0]);
            text3.setText(sb.toString());
            break;
        case Sensor.TYPE_LIGHT:
            sb = new StringBuilder();
            sb.append("光感传感器:\n强度是:");
            sb.append(val[0]);
            text4.setText(sb.toString());
            break;
        case Sensor.TYPE_PRESSURE:
            sb = new StringBuilder();
            sb.append("压力传感器:\n当前压力是:");
            sb.append(val[0]);
            text5.setText(sb.toString());
            break;

    }

    //Log.d(TAG,"onSensorChanged:"+SensorType);

}

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |