Android Pressure Sensor

简介: package zhangphil.sensor;import android.content.Context;import android.
package zhangphil.sensor;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    private SensorManager mSensorManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        startSensor();
    }

    /**
     * 启动传感器。
     */
    private void startSensor() {
        mSensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);

        Sensor mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
        if (mSensorManager == null || mSensor == null) {
            throw new UnsupportedOperationException("设备不支持");
        }

        boolean isRegister = mSensorManager.registerListener(mSensorEventListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
        if (!isRegister) {
            throw new UnsupportedOperationException();
        }
    }

    private SensorEventListener mSensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            if (sensorEvent.sensor.getType() == Sensor.TYPE_PRESSURE) {
                /**
                 * 传感器返回的压强,单位是百帕。
                 */
                float pressure = sensorEvent.values[0];
                Log.d("压强", String.valueOf(pressure) + "百帕");
            }
        }

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

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSensorManager.unregisterListener(mSensorEventListener);
    }
}

相关文章
|
6月前
|
传感器 Java Shell
android 8.1 disable unsupported sensor
android 8.1 disable unsupported sensor
38 0
|
传感器 Android开发
|
传感器 Android开发
|
传感器 Android开发
Android Step Counter & Detector Sensor
package zhangphil.sensor; import android.content.Context; import android.
1149 0
|
传感器 Android开发
Android Orientation Sensor
package zhangphil.sensor; import android.content.Context; import android.
835 0
|
传感器 Android开发
Android Light Sensor
package zhangphil.sensor; import android.content.Context; import android.
972 0
|
传感器 Android开发
Android Accelerometer Sensor
package zhangphil.sensor; import android.content.Context; import android.
874 0
|
传感器 Android开发
Android Proximity Sensor近距离传感器P-Sensor
package zhangphil.sensor; import android.content.Context; import android.
1344 0