这个代码是一个安卓指南针应用程序这个指南针不支持某些设备请帮助我
private SensorManager SensorManage;
// define the compass picture that will be use
private ImageView compassimage;
// record the angle turned of the compass picture
private float DegreeStart = 0f;
TextView DegreeTV;
compassimage = (ImageView) findViewById(R.id.compass_image);
// TextView that will display the degree
DegreeTV = (TextView) findViewById(R.id.DegreeTV);
// initialize your android device sensor capabilities
SensorManage = (SensorManager) getSystemService(SENSOR_SERVICE);
}
这是指南针的方法
@Override
protected void onPause() {
super.onPause();
// to stop the listener and save battery
SensorManage.unregisterListener(this);
}
@Override
protected void onResume() {
super.onResume();
// code for system's orientation sensor registered listeners
SensorManage.registerListener(this, SensorManage.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_GAME);
}
@Override
public void onSensorChanged(SensorEvent event) {
// get angle around the z-axis rotated
float degree = Math.round(event.values[0]);
DegreeTV.setText("Heading: " + Float.toString(degree) + " degrees");
// rotation animation - reverse turn degree degrees
RotateAnimation ra = new RotateAnimation(
DegreeStart,
-degree,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
// set the compass animation after the end of the reservation status
ra.setFillAfter(true);
// set how long the animation for the compass image will take place
ra.setDuration(210);
// Start animation of compass image
compassimage.startAnimation(ra);
DegreeStart = -degree;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// not in use
}
}
答案 0 :(得分:2)
有些设备不支持罗盘,我有相同的问题。然后我将在设备中检查指南针是否支持以下代码。
private SensorManager SensorManage ;
private Sensor sensor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_compass);
this.SensorManage = (SensorManager) getSystemService(SENSOR_SERVICE);
this.sensor = this.SensorManage.getDefaultSensor(Sensor.TYPE_ORIENTATION);
if (this.sensor != null) {
SensorManage.registerListener(this, SensorManage.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME);
} else {
Toast.makeText(this, "Compass Not Supported", Toast.LENGTH_LONG).show();
}
}
希望这会对你有所帮助!
答案 1 :(得分:0)
访问这里,它是一个简单的安卓指南针。你可以按照它的实施。 https://github.com/klein-artur/Simple-Android-Compass-Assistant
示例代码:
@Override
public void onNewSmoothedDegreesToNorth(float degrees) {
final RotateAnimation ra = new RotateAnimation(
currentDegree,
degrees,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF,
0.5f);
ra.setDuration(210);
ra.setFillAfter(true);
this.runOnUiThread(new Runnable() {
@Override
public void run() {
compass.startAnimation(ra);
}
});
currentDegree = degrees;
}
否则,请访问此处了解更多详情 https://developer.android.com/reference/android/hardware/SensorManager
希望这会对你有所帮助。