简单的问题,我遵循了几个教程但我的接近传感器不起作用。我只能以编程方式获得它确实存在的事实,但是当我把手放在接近传感器上时文本没有改变:
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor sensor;
private TextView textView;
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
textView = (TextView) findViewById(R.id.textview);
if(sensor == null) {
textView.setText("No Proximity Sensor found");
}else{
textView.setText(sensor.getName() + " Found");
}
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
if(event.values[0] == 0) {
textView.setText("You are near: " + String.valueOf(event.values[0]));
}else{
textView.setText("You are far: " + String.valueOf(event.values[0]));
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
解决方案:
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor sensor;
private TextView textView;
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
textView = (TextView) findViewById(R.id.textview);
if(sensor == null) {
textView.setText("No Proximity Sensor found");
}else{
textView.setText(sensor.getName() + " Found");
}
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
if(event.values[0] == 0) {
textView.setText("You are near: " + String.valueOf(event.values[0]));
}else{
textView.setText("You are far: " + String.valueOf(event.values[0]));
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
这就是我最终如何运作,感谢所有帮助人员:)
答案 0 :(得分:2)
您忘记将听众附加到传感器:
sensor.registerListener(this);
或者更好的是:
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_FASTEST);