Android Studio开发指南针应用编译正常但启动崩溃求助
问题根因
你遇到的崩溃是典型的空指针异常,错误发生在onSensorChanged方法中:你手动定义了一个空的SensorEvent event = null,直接访问event.sensor就会触发空指针。实际上系统回调传入的sensorEvent参数已经携带了所有传感器数据,不需要你额外定义新的SensorEvent变量。
除此之外你的代码还有几处小问题需要修正:
- 代码里转义导致的
&&要改回正常的逻辑与符号&& - 传感器返回的
orientation[0]是弧度值,需要转换成角度值才符合日常使用的度数规范 - 无效代码
Float.toString(degree);没有赋值,没有实际作用,可以删掉 - 传感器数据未就绪的情况下不要执行旋转动画逻辑,避免异常
修正后的完整onSensorChanged方法代码
@Override public void onSensorChanged(SensorEvent sensorEvent) { float degree = 0f; float[] mGravity = null; float[] mGeomagnetic = null; // 直接用系统传入的sensorEvent,不要自己定义空的event if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) mGravity = sensorEvent.values.clone(); // 加clone避免数据被后续回调覆盖 if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) mGeomagnetic = sensorEvent.values.clone(); 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); // 弧度转角度,取整更易读 degree = Math.round((float) Math.toDegrees(orientation[0])); // 处理负数角度,统一转换成0-360度的格式 degree = (degree + 360) % 360; tvDegree.setText("Degrees from north: " + degree); // 只有拿到有效角度的时候才执行动画 RotateAnimation ra = new RotateAnimation(current_degree, -degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); ra.setDuration(210); ra.setFillAfter(true); ivDinamic.startAnimation(ra); current_degree = -degree; } } }
额外注意事项
- 建议使用真机测试,模拟器默认没有真实的传感器数据,需要手动在模拟器设置里模拟磁力计、加速度计的数值才能看到效果
- 适配高版本安卓系统不需要额外申请传感器相关的动态权限,只要确保设备有磁力计硬件就可以正常运行
内容的提问来源于stack exchange,提问作者Лысый
相关产品推荐
相关产品推荐

