//手机顶部朝上
public static final int UP = 0;
//手机底部朝上
public static final int DOWN = 1;
//手机左边朝上
public static final int LEFT = 2;
//手机右边朝上
public static final int RIGHT = 3;
public int orientation = 0;
@Override
public void onResume() {
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor sensor_gravity=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float x = event.values[0];
float y = event.values[1];
//y的绝对值大于x时,顶部或者底部朝上
if (Math.abs(y) > Math.abs(x)) {
if (y > 0) {
orientation = UP;
}else{
orientation = DOWN;
}
}else{
if (x > 0) {
orientation = LEFT;
}else{
orientation = RIGHT;
}
}
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
}, sensor_gravity, SensorManager.SENSOR_DELAY_UI);
super.onResume();
网友评论