是否有可能在Android中获得接近传感器的当前值?
我知道我可以使用SensorManager和Sensor并注册状态更改的侦听器,但我不需要收到有关每个状态更改的通知,因此这个代码在服务中运行会非常低效。此外,我的代码在状态发生变化之前不会知道该值(如果值没有改变怎么办?如何知道它是什么?相反,我只想说:而不是注册一个监听器,我只想说:
proximitySensor.getCurrentDistance();
这可能吗?
由于
答案 0 :(得分:4)
查看文档后,看起来您可以通过订阅SensorEvent并查看传回的数据来获得以厘米为单位的距离。
在这里开始使用接近传感器有一个很好的例子:Android Proximity Sensor Example
在进一步阅读Android docs之后,看起来数组values[0]
会返回一个厘米的值。注意,看看文档,一些传感器只返回二进制值,这意味着设备要么接近也要远。
答案 1 :(得分:1)
要使用SensorManager访问设备传感器,您必须调用getSystemService(SENSOR_SERVICE)。这是一个例子:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".SensorActivity" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/far" />
</RelativeLayout>
这是java类:
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ImageView;
public class SensorActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mSensor;
ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sensor_screen);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
iv = (ImageView) findViewById(R.id.imageView1);
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
if (event.values[0] == 0) {
iv.setImageResource(R.drawable.near);
} else {
iv.setImageResource(R.drawable.far);
}
}
}