当前位置: 首页 > 工具软件 > Proximity > 使用案例 >

Android——距离传感器(PROXIMITY)的应用

董永宁
2023-12-01

https://blog.csdn.net/Li_peilun/article/details/68921321

有了之前加速传感器的知识,距离传感器也是一样的。

来做一个通过距离传感器来记录你靠近它的次数。

public class MainActivity extends Activity {
    private TextView tv;
    private Sensor sensor;
    private SensorManager sm;
    private SensorEventListener listener;
    private int count;
    private Vibrator vibrator;
    private int mx,my,mz;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv=(TextView) findViewById(R.id.tv);
        }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        sm.unregisterListener(listener);
    }
public void juli(View v)
    {//获得传感器服务
        sm=(SensorManager) getSystemService(Context.SENSOR_SERVICE);
    //获得距离传感器
        sensor=sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        listener=new SensorEventListener() {

            @Override
            public void onSensorChanged(SensorEvent event) {
                // TODO Auto-generated method stub
                //获得距离传感器中的数值,这里只有一个距离
                float juli[]=event.values;
                int distance=(int) juli[0];
                //与默认距离比较
                if(distance<sensor.getMaximumRange())
                {
                    count++;
                    tv.setText(count+"");
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
                // TODO Auto-generated method stub

            }
        };
        sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

}

 

 类似资料: