当我查看xcover 3中的规格时,他们写这个模型有陀螺仪。
我尝试编写代码(我使用android studio)来查看它的工作原理,但它没有在这个模型或android虚拟设备上向我展示这个传感器。
public class Menu extends AppCompatActivity implements SensorEventListener{
boolean running = false;
SensorManager sensorManager;
ToggleButton btn;
TextView textView;
TextView x1;
TextView y1;
TextView z1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
btn = (ToggleButton) findViewById(R.id.toggleButton);
sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
running = true;
}
else{
running = false;
}}
});
}
@Override
protected void onResume() {
super.onResume();
Sensor countsensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if(countsensor != null){
sensorManager.registerListener(this,countsensor,SensorManager.SENSOR_DELAY_FASTEST);
}
else{
Toast.makeText(this, "Brak sensora",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onSensorChanged(SensorEvent event) {
if(running){
x1 =(TextView) findViewById(R.id.textViewX1);
y1 =(TextView) findViewById(R.id.textViewY1);
z1 =(TextView) findViewById(R.id.textViewZ1);
x1.setText(String.valueOf(event.values[0]));
y1.setText(String.valueOf(event.values[1]));
z1.setText(String.valueOf(event.values[2]));
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}}
在这部分countsensor返回null。
@Override
protected void onResume() {
super.onResume();
Sensor countsensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if(countsensor != null){
sensorManager.registerListener(this,countsensor,SensorManager.SENSOR_DELAY_FASEST);
}
else{
Toast.makeText(this, "Brak sensora",Toast.LENGTH_SHORT).show();
}
}
当我将Sensor.TYPE_GYROSCOPE更改为Sensor.TYPE_ACCELEROMETER时,一切正常。 我很困惑,为什么它不起作用。
答案 0 :(得分:1)
根据该网站,该设备没有陀螺仪:
https://www.gsmarena.com/samsung_galaxy_xcover_3-6990.php
您可以使用以下几行代码检查设备中是否存在陀螺仪:
boolean gyro;
gyro = sensorMgr.registerListener(this,sensorMgr.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if(gyro)
{
//code to execute if gyro is present
}