【发布时间】:2020-07-31 08:14:17
【问题描述】:
我正在尝试制作一个以度数显示手机旋转的应用,但没有调用 onSensorChanged。 textView 中的文本没有改变,我不知道为什么。它不会给出任何编译错误。这是代码。
package com.alex.location360;
import androidx.appcompat.app.AppCompatActivity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
TextView textView;
float roll=0;
@Override
public void onSensorChanged(SensorEvent event) {
float[] mGravity = new float[0];
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = event.values;
float[] mGeomagnetic = new float[0];
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = event.values;
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
float azimuth = orientation[0]; // orientation contains: azimuth, pitch and roll
float pitch = orientation[1];
roll = orientation[2];
roll= (float) Math.toDegrees(roll);
textView.setText(String.valueOf(roll));
Log.e("#",String.valueOf(roll));
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.textView);
}
}
【问题讨论】:
-
在传感器运行时设置断点已更改。如果在您的 oncreate 中检查,您可以在代码中手动设置 textview。
textView.setTest("Does this work?");如果成功的话,你还有一个带有日志语句的 else 来查看 ti 是否在 logcat 中工作。 -
@ThomasMorris sensorChanged 根本没有被访问。
-
好的,我建议您查看文档以了解您应该如何使用它。你在哪里声明传感器。您的传感器也需要权限。通过加速,您可能需要权限,请参阅:developer.android.com/guide/topics/sensors/sensors_motion
标签: java android android-sensors sensormanager