我的新应用程序面临挑战,我想找到面向天花板或地板的 android 手机屏幕。我能用 android 传感器做到这一点。如果有人尝试过这个,请分享您的宝贵想法和教程(如果有)。
问问题
328 次
2 回答
1
您可以使用SensorEventListener
来实现这一点。请查看我的以下代码以更好地理解。您还可以在开发人员文档中查看有关传感器的更多信息。
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class SensorClass implements SensorEventListener {
private float mInR[];
private float mI[];
private float mGravity[];
private float mGeomag[];
private float mOrientVals[];
final float rad2deg = 180/((float) Math.PI);
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here when accuracy changed
}
@Override
public void onSensorChanged(SensorEvent event) {
float azimuth = 0f;
float pitch = 0f;
float roll = 0f;
// If the sensor data is unreliable return
if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
return;
// Gets the value of the sensor that has been changed
switch (event.sensor.getType()){
case Sensor.TYPE_ACCELEROMETER:
mGravity = event.values.clone();
break;
case Sensor.TYPE_MAGNETIC_FIELD:
mGeomag = event.values.clone();
break;
}
if (mGravity != null && mGeomag != null){
// checks that the rotation matrix is found
if (SensorManager.getRotationMatrix(mInR, mI, mGravity, mGeomag)){
// magnetic north and the horizon respectively
SensorManager.getOrientation(mInR, mOrientVals);
azimuth = mOrientVals[0]*rad2deg;
pitch = mOrientVals[1]*rad2deg;
roll = mOrientVals[2]*rad2deg;
}
}
}
}
于 2013-03-14T10:43:46.593 回答
1
在oncreate
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
List<Sensor> sensorList = sensorManager
.getSensorList(Sensor.TYPE_ACCELEROMETER);
if (sensorList.size() > 0) {
accelerometerPresent = true;
accelerometerSensor = sensorList.get(0);
}
注册SensorEventListener
sensorManager.registerListener(accelerometerListener,
accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
和SensorEventListener
实施
private SensorEventListener accelerometerListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
float z_value = event.values[2];
if (z_value == 10) {
// up facing
} else if(z_value == -10)
// down facing
}
}
};
在我的两个设备中,当它朝上和水平时它显示 z_values = 10,而在相反的情况下它显示 - 10。检查你的案例。
于 2013-03-14T10:51:01.387 回答