简体   繁体   English

无法在android中获取接近传感器的值

[英]Not able to get proximity sensor's values in android

Can someone provide an example as to how to use the proximity sensor? 有人可以举例说明如何使用接近传感器吗? I tried to use it the same way as other sensors, but it's not working. 我尝试以与其他传感器相同的方式使用它,但它不起作用。

This is the code snippet i have been using: 这是我一直在使用的代码片段:

 final SensorManager mSensorManager;
 final Sensor mproximity;

mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mproximity =  mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);

mSensorManager.registerListener(new SensorListener(){

public void onAccuracyChanged(int arg0, int arg1) {
   // TODO Auto-generated method stub
   Toast.makeText(test.this,"proximity sensor accu ", Toast.LENGTH_SHORT).show();
}

public void onSensorChanged(int arg0, float[] arg1) {
   // TODO Auto-generated method stub
   Toast.makeText(test.this,"proximity sensor ", Toast.LENGTH_SHORT).show();
}

}, Sensor.TYPE_PROXIMITY, 1);

Please tell me where I am going wrong. 请告诉我哪里出错了。

The method registerListener(SensorListener, int, int) is deprecated, use registerListener(SensorEventListener, Sensor, int) instead: 该方法registerListener(SensorListener, int, int)已过时,使用registerListener(SensorEventListener, Sensor, int)代替:

mSensorManager.registerListener(proximityListener,
        mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY),
        SensorManager.SENSOR_DELAY_UI);

Furthermore you should save a reference to your Sensor(Event)Listener , to be able to unregister it. 此外,您应该保存对Sensor(Event)Listener的引用,以便能够取消注册它。

Gubbel makes a valid point. Gubbel提出了一个有效的观点。 Please use the latest API. 请使用最新的API。

Also do note that the proximity sensor is implemented differently from 另请注意,接近传感器的实现方式与之不同
the other sensors. 其他传感器。 While the other sensors can be "polled" the 而其他传感器可以“轮询”了
proximity sensor is interrupt based. 接近传感器是基于中断的。

So you get a onSensorChanged event ONLY when a proximity state 因此,只有在接近状态时才会获得onSensorChanged事件
transition occurs (ie near-to-far or far-to-near). 过渡发生(即近远或远近)。

Often the proximity sensor is implemented using the light-sensor hardware. 通常,接近传感器使用光传感器硬件实现。
So, you can launch your app and cover/uncover the light-sensor on the top 因此,您可以启动应用程序并覆盖/揭开顶部的光传感器
of your device. 你的设备。 Doing so will trigger the proximity-sensor transitions 这样做会触发接近传感器转换
and you will surely get data (0/1 or far/near) in your app then. 然后你肯定会在你的应用程序中获取数据(0/1或远/近)。

More info on Proximity sensor on Android . 有关Android接近传感器的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM