有人可以举例说明如何使用接近传感器吗?请描述一些事件以及如何使用它们。
答案 0 :(得分:4)
每个Android手机都附带传感器来测量各种环境条件。接近传感器测量某个物体距设备的距离。它通常用于检测设备旁边是否存在人脸。
某些接近传感器仅支持二进制近或远测量。在这种情况下,传感器应报告远态的最大范围值和近状态的较小值。
package com.exercise.AndroidProximitySensor;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class AndroidProximitySensorActivity extends Activity {
/** Called when the activity is first created. */
TextView ProximitySensor, ProximityMax, ProximityReading;
SensorManager mySensorManager;
Sensor myProximitySensor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ProximitySensor = (TextView)findViewById(R.id.proximitySensor);
ProximityMax = (TextView)findViewById(R.id.proximityMax);
ProximityReading = (TextView)findViewById(R.id.proximityReading);
mySensorManager = (SensorManager)getSystemService(
Context.SENSOR_SERVICE);
myProximitySensor = mySensorManager.getDefaultSensor(
Sensor.TYPE_PROXIMITY);
if (myProximitySensor == null){
ProximitySensor.setText("No Proximity Sensor!");
}else{
ProximitySensor.setText(myProximitySensor.getName());
ProximityMax.setText("Maximum Range: "
+ String.valueOf(myProximitySensor.getMaximumRange()));
mySensorManager.registerListener(proximitySensorEventListener,
myProximitySensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
SensorEventListener proximitySensorEventListener
= new SensorEventListener(){
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if(event.sensor.getType()==Sensor.TYPE_PROXIMITY){
ProximityReading.setText("Proximity Sensor Reading:"
+ String.valueOf(event.values[0]));
}
}
};
}
上面代码的布局xml如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/proximitySensor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/proximityMax"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/proximityReading"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
在上面的示例中,我们有3个textview。第一个是显示设备是否支持接近传感器,第二个显示传感器支持的最大范围,第三个显示当前读数。
希望这能让您了解接近传感器的基本知识。