目录
[android 相机判断水平java代码](#android 相机判断水平java代码)
添加权限:
bash
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature android:name="android.hardware.sensor.accelerometer"/>
<uses-feature android:name="android.hardware.sensor.gyroscope"/>
android 相机判断水平java代码
java
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometer;
private Sensor gyroscope;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
gyroscope = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this, gyroscope, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this, gyroscope, 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_ACCELEROMETER) {
float[] gravity = event.values;
float x = gravity[0];
float y = gravity[1];
float z = gravity[2];
double angle = Math.toDegrees(Math.acos(z / Math.sqrt(x * x + y * y + z * z)));
// 判断设备是否水平
if (angle < 5) {
Toast.makeText(this, "设备水平", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "设备不水平", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// 不需要实现
}
}