作者:mobiledu2502871703 | 来源:互联网 | 2023-10-15 13:47
通常手机自带的距离传感器只能检测到几厘米的范围,一般用于判断手机在不在口袋中importandroid.content.Context;importandroid.hardwar
通常手机自带的距离传感器只能检测到几厘米的范围,一般用于判断手机在不在口袋中
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
public class ProximitySensor implements SensorEventListener {
private static final String TAG = "ProximitySensor";
private static ProximitySensor instance;
private SensorManager mSensorManager;
private float distance = -1;
private boolean mHasStarted = false;
private ProximitySensor() {
}
public static ProximitySensor getInstance() {
if (instance == null) {
instance = new ProximitySensor();
}
return instance;
}
/**
* 启动距离传感器
*/
public static void start(Context context) {
ProximitySensor.getInstance().registerListener(context);
}
/**
* 停止距离传感器
*/
public static void stop() {
ProximitySensor.getInstance().unregisterListener();
}
/**
* 获取手机距离(单位厘米)
*/
public static float getDistance() {
return ProximitySensor.getInstance().getValue();
}
// ------------------------------------------------------------------------------
/**
* Use this method to start listening of the sensor
*/
private void registerListener(Context context) {
if (mHasStarted) {
return;
}
mHasStarted = true;
mSensorManager = (SensorManager) context.getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
Sensor proximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); // 获取距离传感器
if (proximitySensor != null) { // 距离传感器存在时才执行
mSensorManager.registerListener(this, proximitySensor, SensorManager.SENSOR_DELAY_NORMAL); // 注册事件监听
}
}
/**
* Use this method to stop listening of the sensor
*/
private void unregisterListener() {
if (!mHasStarted || mSensorManager == null) {
return;
}
mHasStarted = false;
mSensorManager.unregisterListener(this);
}
private float getValue() {
if (!mHasStarted) {
Log.w(TAG, "proximity sensor has not start!");
}
return distance;
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event != null && event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
// values[0]: Proximity sensor distance measured in centimeters
distance = event.values[0];
Log.v(TAG, "proximity sensor distance: " + distance);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}