Sensor(PROXIMITY)

package com.example.sensor01;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity implements SensorEventListener {

    private SensorManager mSensorManager;
    private TextView textview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textview = (TextView) findViewById(R.id.content);

        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        
        //距离传感器通常用于确定用户头部与手持设备屏幕表面的距离(比如,用户拨打或接听电话时脸贴近屏幕会亮等)。 
        //大部分距离传感器返回的是绝对距离,单位是 cm,也有返回其他的,比如我手头这台华为,只返回0,5两个值。
        Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);

        mSensorManager.registerListener(this, sensor,
                SensorManager.SENSOR_DELAY_NORMAL);

    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        float distance = 0;
        if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {

            distance = event.values[0];
        }
        textview.setText(String.valueOf(distance));
    }
}

 

你可能感兴趣的:(sensor)