我用這個代碼:
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mProximity;
private static final int SENSOR_SENSITIVITY = 4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
if (event.values[0] >= -SENSOR_SENSITIVITY && event.values[0] <= SENSOR_SENSITIVITY) {
//near
Toast.makeText(getApplicationContext(), "near", Toast.LENGTH_SHORT).show();
} else {
//far
Toast.makeText(getApplicationContext(), "far", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
你也可以check this code in GitHub
你能告訴設置代碼? – Ifor
在android上有**接近傳感器**的多個教程。首先,通過閱讀這篇[關於Android **上的接近傳感器的文章](http://thecodeartist.blogspot.in/2011/01/proximity-sensor-on-android-gingerbread.html)來開發正確的理解。接下來,以下教程[** 1 **](http://androidbite.blogspot.in/2013/05/android-proximity-sensor-example.html)和[** 2 **](http:// velmuruganandroidcoding.blogspot.in/2013/05/proximity-sensor-in-android-example.html)應該有所幫助。另外我會建議你在具有接近傳感器的真實設備上運行你的代碼,因爲它是非常直接的 – Rahil2952
運行示例http://androidbite.blogspot.com/2013/05/android-proximity-sensor-example。 html –